helia 7.0.1 → 7.0.2
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 +9 -9
- package/dist/index.min.js.map +3 -3
- package/dist/src/helia.d.ts +3 -2
- package/dist/src/helia.d.ts.map +1 -1
- package/dist/src/helia.js +16 -9
- package/dist/src/helia.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +6 -6
- package/src/helia.ts +20 -11
- 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 nD=Object.create;var ch=Object.defineProperty;var oD=Object.getOwnPropertyDescriptor;var sD=Object.getOwnPropertyNames;var iD=Object.getPrototypeOf,aD=Object.prototype.hasOwnProperty;var sn=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},V=(r,e)=>{for(var t in e)ch(r,t,{get:e[t],enumerable:!0})},mb=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sD(e))!aD.call(r,o)&&o!==t&&ch(r,o,{get:()=>e[o],enumerable:!(n=oD(e,o))||n.enumerable});return r};var ti=(r,e,t)=>(t=r!=null?nD(iD(r)):{},mb(e||!r||!r.__esModule?ch(t,"default",{value:r,enumerable:!0}):t,r)),cD=r=>mb(ch({},"__esModule",{value:!0}),r);var o4=sn(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.Netmask4Impl=void 0;Oa.ip2long=Na;Oa.long2ip=Mn;function Mn(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var xN=48,EN=97,vN=65;function SN(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-xN)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-EN)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-vN)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function Na(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=SN(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var n4=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Na(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Na(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=Mn(this.netLong),this.mask=Mn(this.maskLong),this.hostmask=Mn(~this.maskLong),this.first=this.bitmask<=30?Mn(this.netLong+1):this.base,this.last=this.bitmask<=30?Mn(this.netLong+this.size-2):Mn(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Mn(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):(Na(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Mn(this.netLong+this.size*e),this.mask)}forEach(e){let t=Na(this.first),n=Na(this.last),o=0;for(;t<=n;)e(Mn(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};Oa.Netmask4Impl=n4});var g9=sn(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.Netmask6Impl=void 0;Ba.ip6bigint=i4;Ba.bigint2ip6=xi;var AN=o4(),s4=(1n<<128n)-1n;function i4(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,AN.ip2long)(n),s=r.substring(0,t+1)+"0:0";return m9(s)&~0xffffffffn|BigInt(o)}return m9(r)}function m9(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.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 o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function xi(r){if(r<0n||r>s4)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,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),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 a4=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=s4>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=i4(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=xi(this.netBigint),this.mask=xi(this.maskBigint),this.hostmask=xi(~this.maskBigint&s4),this.first=this.base,this.last=xi(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):(i4(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(xi(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(xi(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Ba.Netmask6Impl=a4});var y9=sn(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.long2ip=ss.ip2long=ss.Netmask=void 0;var Uh=o4();Object.defineProperty(ss,"ip2long",{enumerable:!0,get:function(){return Uh.ip2long}});Object.defineProperty(ss,"long2ip",{enumerable:!0,get:function(){return Uh.long2ip}});var IN=g9(),c4=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 IN.Netmask6Impl(e,t):this._impl=new Uh.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 Uh.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()}};ss.Netmask=c4});var dA=sn((Ppe,Ny)=>{"use strict";var AF=Object.prototype.hasOwnProperty,fr="~";function Td(){}Object.create&&(Td.prototype=Object.create(null),new Td().__proto__||(fr=!1));function IF(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function uA(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new IF(t,n||r,o),i=fr?fr+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function x0(r,e){--r._eventsCount===0?r._events=new Td:delete r._events[e]}function Zt(){this._events=new Td,this._eventsCount=0}Zt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)AF.call(t,n)&&e.push(fr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Zt.prototype.listeners=function(e){var t=fr?fr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Zt.prototype.listenerCount=function(e){var t=fr?fr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Zt.prototype.emit=function(e,t,n,o,s,i){var a=fr?fr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,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,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};Zt.prototype.on=function(e,t,n){return uA(this,e,t,n,!1)};Zt.prototype.once=function(e,t,n){return uA(this,e,t,n,!0)};Zt.prototype.removeListener=function(e,t,n,o){var s=fr?fr+e:e;if(!this._events[s])return this;if(!t)return x0(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&x0(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:x0(this,s)}return this};Zt.prototype.removeAllListeners=function(e){var t;return e?(t=fr?fr+e:e,this._events[t]&&x0(this,t)):(this._events=new Td,this._eventsCount=0),this};Zt.prototype.off=Zt.prototype.removeListener;Zt.prototype.addListener=Zt.prototype.on;Zt.prefixed=fr;Zt.EventEmitter=Zt;typeof Ny<"u"&&(Ny.exports=Zt)});var pA=sn((Jpe,hA)=>{hA.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var DA=sn((mge,LA)=>{"use strict";function QF(r){return r>=55296&&r<=56319}function JF(r){return r>=56320&&r<=57343}LA.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,s=0,i,a,c=0;c<o;c+=1){if(i=t.charCodeAt(c),a=t[c],QF(i)&&JF(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),s+=e(a),s===n)return t.slice(0,c+1);if(s>n)return t.slice(0,c-a.length+1)}return t}});var NA=sn((gge,RA)=>{"use strict";function ZF(r){return r>=55296&&r<=56319}function e$(r){return r>=56320&&r<=57343}RA.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,s=null,i=0;i<t;i++)o=e.charCodeAt(i),e$(o)?s!=null&&ZF(s)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),s=o;return n}});var BA=sn((yge,OA)=>{"use strict";var t$=DA(),r$=NA();OA.exports=t$.bind(null,r$)});var i8=sn((wge,UA)=>{"use strict";var n$=BA(),o$=/[\/\?<>\\:\*\|"]/g,s$=/[\x00-\x1f\x80-\x9f]/g,i$=/^\.+$/,a$=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function c$(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 MA(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(o$,e).replace(s$,e).replace(i$,e).replace(a$,e);return t=c$(t,e),n$(t,255)}UA.exports=function(r,e){var t=e&&e.replacement||"",n=MA(r,t);return t===""?n:MA(n,"")}});var FA=sn(Oc=>{"use strict";var u$="[object ArrayBuffer]",Bo=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===u$}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])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 o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},c8="string",d$=/^[0-9a-f\s]+$/i,f$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,h$=/^[a-zA-Z0-9-_]+$/,H0=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Bo.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},rn=class{static toString(e,t=!1){let n=Bo.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},q0=class r{static isHex(e){return typeof e===c8&&d$.test(e)}static isBase64(e){return typeof e===c8&&f$.test(e)}static isBase64Url(e){return typeof e===c8&&h$.test(e)}static ToString(e,t="utf8"){let n=Bo.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 rn.toString(n,!0);case"utf16":case"utf16be":return rn.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 rn.fromString(e,!0);case"utf16":case"utf16be":return rn.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Bo.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 H0.fromString(e);case"utf16":case"utf16be":return rn.fromString(e);case"utf16le":case"usc2":return rn.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 H0.toString(e);case"utf16":case"utf16be":return rn.toString(e);case"utf16le":case"usc2":return rn.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Bo.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Bo.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];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 o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return rn.toString(e,t)}static FromUtf16String(e,t=!1){return rn.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,"")||""}};q0.DEFAULT_UTF8_ENCODING="utf8";function p$(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function m$(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function g$(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Oc.BufferSourceConverter=Bo;Oc.Convert=q0;Oc.assign=p$;Oc.combine=m$;Oc.isEqual=g$});var R_=sn(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.parseCookie=L_;lo.parse=L_;lo.stringifyCookie=WG;lo.stringifySetCookie=R2;lo.serialize=R2;lo.parseSetCookie=GG;lo.stringifySetCookie=R2;lo.serialize=R2;var __=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,P_=/^[\u0021-\u003A\u003C-\u007E]*$/,KG=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,VG=/^[\u0020-\u003A\u003D-\u007E]*$/,HG=/^-?\d+$/,qG=Object.prototype.toString,zG=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function L_(r,e){let t=new zG,n=r.length;if(n<2)return t;let o=e?.decode||D_,s=0;do{let i=bw(r,s,n);if(i===-1)break;let a=ww(r,s,n);if(i>a){s=r.lastIndexOf(";",i-1)+1;continue}let c=Hs(r,s,i);t[c]===void 0&&(t[c]=o(Hs(r,i+1,a))),s=a+1}while(s<n);return t}function WG(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let o of Object.keys(r)){let s=r[o];if(s===void 0)continue;if(!__.test(o))throw new TypeError(`cookie name is invalid: ${o}`);let i=t(s);if(!P_.test(i))throw new TypeError(`cookie val is invalid: ${s}`);n.push(`${o}=${i}`)}return n.join("; ")}function R2(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},s=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!__.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let i=n.value?s(n.value):"";if(!P_.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(!KG.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!VG.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!jG(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 GG(r,e){let t=e?.decode||D_,n=r.length,o=ww(r,0,n),s=bw(r,0,o),i=s===-1?{name:"",value:t(Hs(r,0,o))}:{name:Hs(r,0,s),value:t(Hs(r,s+1,o))},a=o+1;for(;a<n;){let c=ww(r,a,n),l=bw(r,a,c),u=l===-1?Hs(r,a,c):Hs(r,a,l),d=l===-1?void 0:Hs(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&&HG.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 ww(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function bw(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Hs(r,e,t){let n=e,o=t;do{let s=r.charCodeAt(n);if(s!==32&&s!==9)break}while(++n<o);for(;o>n;){let s=r.charCodeAt(o-1);if(s!==32&&s!==9)break;o--}return r.slice(n,o)}function D_(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function jG(r){return qG.call(r)==="[object Date]"}});var ZY={};V(ZY,{DEFAULT_CID_PEER_FILTER_SIZE:()=>j3,DEFAULT_SESSION_MAX_PROVIDERS:()=>G3,DEFAULT_SESSION_MIN_PROVIDERS:()=>W3,InsufficientProvidersError:()=>au,InvalidCodecError:()=>Y3,NoRoutersAvailableError:()=>os,UnknownCodecError:()=>lu,UnknownCryptoError:()=>uu,UnknownHashAlgorithmError:()=>cu,createHelia:()=>JY,createHeliaLight:()=>rD,isPrivateKey:()=>r9,isPublicKey:()=>z3});var gb=Symbol.for("@libp2p/connection");var ri=Symbol.for("@libp2p/content-routing");var nr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},lh=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},uh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},A=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},fo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},$l=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Kl=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var ni=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},ba=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},an=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},xa=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Nn=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Vl=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Te=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ea=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},On=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},dh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},va=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},fh=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},pe=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},oi=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Bn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Cr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Zo=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},si=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Hl=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},hh=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Sa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},cn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ph=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},es=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},mh=class extends es{constructor(e,t){super(!0,e,t)}},gh=class extends es{constructor(e,t){super(!1,e,t)}};var ii=Symbol.for("@libp2p/peer-discovery");var yh=Symbol.for("@libp2p/peer-id");function yr(r){return!!r?.[yh]}var ai=Symbol.for("@libp2p/peer-routing");var ci="keep-alive";function wh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ht(...r){let e=[];for(let t of r)wh(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 Ct(...r){let e=[];for(let t of r)wh(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 ts=Symbol.for("@libp2p/transport");var ql;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(ql||(ql={}));function lD(r){return typeof r?.handleEvent=="function"}function uD(r){return(r!==!0&&r!==!1&&r?.once)??!1}var le=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=uD(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}lD(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var xe=Symbol.for("@libp2p/service-capabilities"),kr=Symbol.for("@libp2p/service-dependencies");var R=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function de(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var FX=new Uint8Array(0);function wb(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 wr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return li(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return li(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function bb(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var yb=4096;function xb(r){let e=r.length;if(e<=yb)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=yb));return t}function dD(r){return r?.buffer instanceof ArrayBuffer}function li(r){return dD(r)?r:r.slice()}var n3={};V(n3,{base32:()=>pt,base32hex:()=>ED,base32hexpad:()=>SD,base32hexpadupper:()=>AD,base32hexupper:()=>vD,base32pad:()=>bD,base32padupper:()=>xD,base32upper:()=>wD,base32z:()=>ID});function fD(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}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 w=0,x=0,E=0,S=m.length;E!==S&&m[E]===0;)E++,w++;for(var T=(S-E)*h+1>>>0,I=new Uint8Array(T);E!==S;){for(var C=m[E],U=0,j=T-1;(C!==0||U<x)&&j!==-1;j--,U++)C+=256*I[j]>>>0,I[j]=C%u>>>0,C=C/u>>>0;if(C!==0)throw new Error("Non-zero carry");x=U,E++}for(var z=T-x;z!==T&&I[z]===0;)z++;for(var v=d.repeat(w);z<T;++z)v+=r.charAt(I[z]);return v}function y(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var w=0;if(m[w]!==" "){for(var x=0,E=0;m[w]===d;)x++,w++;for(var S=(m.length-w)*f+1>>>0,T=new Uint8Array(S);m[w];){var I=n[m.charCodeAt(w)];if(I===255)return;for(var C=0,U=S-1;(I!==0||C<E)&&U!==-1;U--,C++)I+=u*T[U]>>>0,T[U]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");E=C,w++}if(m[w]!==" "){for(var j=S-E;j!==S&&T[j]===0;)j++;for(var z=new Uint8Array(x+(S-j)),v=x;j!==S;)z[v++]=T[j++];return z}}}function g(m){var w=y(m);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:y,decode:g}}var hD=fD,pD=hD,Eb=pD;var Zg=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")}},e3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return vb(this,e)}},t3=class{decoders;constructor(e){this.decoders=e}or(e){return vb(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 vb(r,e){return new t3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var r3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Zg(e,t,n),this.decoder=new e3(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Aa({name:r,prefix:e,encode:t,decode:n}){return new r3(r,e,t,n)}function rs({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Eb(t,r,n);return Aa({prefix:e,name:r,encode:o,decode:i=>wr(s(i))})}function mD(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function gD(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function yD(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function ot({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=yD(n,o);return Aa({prefix:e,name:r,encode(i){return gD(i,n,t)},decode(i){return mD(i,s,t,r)}})}var pt=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),wD=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),bD=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),xD=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),ED=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),vD=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),SD=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),AD=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),ID=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var o3={};V(o3,{base36:()=>or,base36upper:()=>TD});var or=rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),TD=rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var s3={};V(s3,{base58btc:()=>ge,base58flickr:()=>CD});var ge=rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),CD=rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ze={};V(ze,{Digest:()=>ui,create:()=>sr,decode:()=>Ee,equals:()=>a3,hasCode:()=>WD});var kD=Ib,Sb=128,_D=127,PD=~_D,LD=Math.pow(2,31);function Ib(r,e,t){e=e||[],t=t||0;for(var n=t;r>=LD;)e[t++]=r&255|Sb,r/=128;for(;r&PD;)e[t++]=r&255|Sb,r>>>=7;return e[t]=r|0,Ib.bytes=t-n+1,e}var DD=i3,RD=128,Ab=127;function i3(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw i3.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ab)<<o:(i&Ab)*Math.pow(2,o),o+=7}while(i>=RD);return i3.bytes=s-n,t}var ND=Math.pow(2,7),OD=Math.pow(2,14),BD=Math.pow(2,21),MD=Math.pow(2,28),UD=Math.pow(2,35),FD=Math.pow(2,42),$D=Math.pow(2,49),KD=Math.pow(2,56),VD=Math.pow(2,63),HD=function(r){return r<ND?1:r<OD?2:r<BD?3:r<MD?4:r<UD?5:r<FD?6:r<$D?7:r<KD?8:r<VD?9:10},qD={encode:kD,decode:DD,encodingLength:HD},zD=qD,zl=zD;function Wl(r,e=0){return[zl.decode(r,e),zl.decode.bytes]}function Ia(r,e,t=0){return zl.encode(r,e,t),e}function Ta(r){return zl.encodingLength(r)}function sr(r,e){let t=e.byteLength,n=Ta(r),o=n+Ta(t),s=new Uint8Array(o+t);return Ia(r,s,0),Ia(t,s,n),s.set(e,o),new ui(r,t,e,s)}function Ee(r){let e=wr(r),[t,n]=Wl(e),[o,s]=Wl(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ui(t,o,i,e)}function a3(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&wb(r.bytes,t.bytes)}}var ui=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=li(n),this.bytes=li(o)}};function WD(r,e){return r.code===e}function Tb(r,e){let{bytes:t,version:n}=r;return n===0?jD(t,c3(r),e??ge.encoder):YD(t,c3(r),e??pt.encoder)}var Cb=new WeakMap;function c3(r){let e=Cb.get(r);if(e==null){let t=new Map;return Cb.set(r,t),t}return e}var K=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=li(o),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!==Gl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==XD)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=sr(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&&a3(e.multihash,n.multihash)}toString(e){return Tb(this,e)}toJSON(){return{"/":Tb(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??kb(n,o,s.bytes))}else if(t[QD]===!0){let{version:n,multihash:o,code:s}=t,i=Ee(o);return r.create(n,s,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!==Gl)throw new Error(`Version 0 CID must use dag-pb (code: ${Gl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=kb(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Gl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=wr(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new ui(t.multihashCode,t.digestSize,s,o);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]=Wl(e.subarray(t));return t+=f,d},o=n(),s=Gl;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=GD(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return c3(s).set(n,e),s}};function GD(r,e){switch(r[0]){case"Q":{let t=e??ge;return[ge.prefix,t.decode(`${ge.prefix}${r}`)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case pt.prefix:{let t=e??pt;return[pt.prefix,t.decode(r)]}case or.prefix:{let t=e??or;return[or.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 jD(r,e,t){let{prefix:n}=t;if(n!==ge.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function YD(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Gl=112,XD=18;function kb(r,e,t){let n=Ta(r),o=n+Ta(e),s=new Uint8Array(o+t.byteLength);return Ia(r,s,0),Ia(e,s,n),s.set(t,o),s}var QD=Symbol.for("@ipld/js-cid/CID");var JD=20;function jl({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new l3(r,e,t,n,o)}var l3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??JD,this.maxDigestLength=s}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?_b(n,this.code,t?.truncate):n.then(o=>_b(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _b(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 sr(e,r)}var u3={};V(u3,{base64:()=>$e,base64pad:()=>Yl,base64url:()=>ne,base64urlpad:()=>ZD});var $e=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yl=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ne=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ZD=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var d3={};V(d3,{identity:()=>Ze});var Lb=0,eR="identity",Db=wr;function tR(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 sr(Lb,Db(r))}var Ze={code:Lb,name:eR,encode:Db,digest:tR};function me(r=0){return new Uint8Array(r)}function st(r=0){return new Uint8Array(r)}function rR(r){return r?.buffer instanceof ArrayBuffer}function xh(r){if(rR(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ke(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=st(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return xh(t)}function te(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 Nb=Symbol.for("@achingbrain/uint8arraylist");function Rb(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ca(r){return!!r?.[Nb]}var Y=class r{bufs;length;[Nb]=!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(Ca(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ca(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=Rb(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Rb(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(Ca(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ke(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ke(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(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(!Ca(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;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=st(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=me(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=me(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=me(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=st(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=me(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=me(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=me(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=me(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=me(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function nR(r){return r.buffer instanceof ArrayBuffer}function ee(r){return nR(r)?r:r.slice()}var oR=parseInt("11111",2),f3=parseInt("10000000",2),sR=parseInt("01111111",2),Ob={0:Xl,1:Xl,2:iR,3:lR,4:uR,5:cR,6:aR,16:Xl,22:Xl,48:Xl};function ln(r,e={offset:0}){let t=r[e.offset]&oR;if(e.offset++,Ob[t]!=null)return Ob[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Ql(r,e){let t=0;if((r[e.offset]&f3)===f3){let n=r[e.offset]&sR,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Xl(r,e){Ql(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ln(r,e);if(n===null)break;t.push(n)}return t}function iR(r,e){let t=Ql(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function aR(r,e){let t=Ql(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${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 cR(r,e){return e.offset++,null}function lR(r,e){let t=Ql(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function uR(r,e){let t=Ql(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function dR(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Eh(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=dR(r.byteLength);return new Y(Uint8Array.from([e.byteLength|f3]),e)}function ir(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),Eh(e),e)}function Jl(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),Eh(t),t)}function Bb(r){return new Y(Uint8Array.from([4]),Eh(r),r)}function un(r,e=48){let t=new Y;for(let n of r)t.append(ee(n.subarray()));return new Y(Uint8Array.from([e]),Eh(t),t)}var Ve=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var fR=Math.pow(2,7),hR=Math.pow(2,14),pR=Math.pow(2,21),h3=Math.pow(2,28),p3=Math.pow(2,35),m3=Math.pow(2,42),g3=Math.pow(2,49),Le=128,Wt=127;function we(r){if(r<fR)return 1;if(r<hR)return 2;if(r<pR)return 3;if(r<h3)return 4;if(r<p3)return 5;if(r<m3)return 6;if(r<g3)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ka(r,e,t=0){switch(we(r)){case 8:e[t++]=r&255|Le,r/=128;case 7:e[t++]=r&255|Le,r/=128;case 6:e[t++]=r&255|Le,r/=128;case 5:e[t++]=r&255|Le,r/=128;case 4:e[t++]=r&255|Le,r>>>=7;case 3:e[t++]=r&255|Le,r>>>=7;case 2:e[t++]=r&255|Le,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function mR(r,e,t=0){switch(we(r)){case 8:e.set(t++,r&255|Le),r/=128;case 7:e.set(t++,r&255|Le),r/=128;case 6:e.set(t++,r&255|Le),r/=128;case 5:e.set(t++,r&255|Le),r/=128;case 4:e.set(t++,r&255|Le),r>>>=7;case 3:e.set(t++,r&255|Le),r>>>=7;case 2:e.set(t++,r&255|Le),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function y3(r,e){let t=r[e],n=0;if(n+=t&Wt,t<Le||(t=r[e+1],n+=(t&Wt)<<7,t<Le)||(t=r[e+2],n+=(t&Wt)<<14,t<Le)||(t=r[e+3],n+=(t&Wt)<<21,t<Le)||(t=r[e+4],n+=(t&Wt)*h3,t<Le)||(t=r[e+5],n+=(t&Wt)*p3,t<Le)||(t=r[e+6],n+=(t&Wt)*m3,t<Le)||(t=r[e+7],n+=(t&Wt)*g3,t<Le))return n;throw new RangeError("Could not decode varint")}function gR(r,e){let t=r.get(e),n=0;if(n+=t&Wt,t<Le||(t=r.get(e+1),n+=(t&Wt)<<7,t<Le)||(t=r.get(e+2),n+=(t&Wt)<<14,t<Le)||(t=r.get(e+3),n+=(t&Wt)<<21,t<Le)||(t=r.get(e+4),n+=(t&Wt)*h3,t<Le)||(t=r.get(e+5),n+=(t&Wt)*p3,t<Le)||(t=r.get(e+6),n+=(t&Wt)*m3,t<Le)||(t=r.get(e+7),n+=(t&Wt)*g3,t<Le))return n;throw new RangeError("Could not decode varint")}function Gt(r,e,t=0){return e==null&&(e=st(we(r))),e instanceof Uint8Array?ka(r,e,t):mR(r,e,t)}function _r(r,e=0){return r instanceof Uint8Array?y3(r,e):gR(r,e)}var w3=new Float32Array([-0]),ns=new Uint8Array(w3.buffer);function Mb(r,e,t){w3[0]=r,e[t]=ns[0],e[t+1]=ns[1],e[t+2]=ns[2],e[t+3]=ns[3]}function Ub(r,e){return ns[0]=r[e],ns[1]=r[e+1],ns[2]=r[e+2],ns[3]=r[e+3],w3[0]}var b3=new Float64Array([-0]),jt=new Uint8Array(b3.buffer);function Fb(r,e,t){b3[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3],e[t+4]=jt[4],e[t+5]=jt[5],e[t+6]=jt[6],e[t+7]=jt[7]}function $b(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],jt[4]=r[e+4],jt[5]=r[e+5],jt[6]=r[e+6],jt[7]=r[e+7],b3[0]}var yR=BigInt(Number.MAX_SAFE_INTEGER),wR=BigInt(Number.MIN_SAFE_INTEGER),Pr=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 di;if(e<yR&&e>wR)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Kb&&(o=0n,++n>Kb&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return di;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):di}},di=new Pr(0,0);di.toBigInt=function(){return 0n};di.zzEncode=di.zzDecode=function(){return this};di.length=function(){return 1};var Kb=4294967296n;function Vb(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 Hb(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function x3(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function dn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function vh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var E3=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ee(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,dn(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 dn(this,4);return vh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw dn(this,4);return vh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw dn(this,4);let e=Ub(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw dn(this,4);let e=$b(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 dn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hb(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw dn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw dn(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 Pr(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 dn(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 dn(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 dn(this,8);let e=vh(this.buf,this.pos+=4),t=vh(this.buf,this.pos+=4);return new Pr(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=y3(this.buf,this.pos);return this.pos+=we(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 Zl(r){return new E3(r instanceof Uint8Array?r:r.subarray())}function oe(r,e,t){let n=Zl(r);return e.decode(n,void 0,t)}var v3={};V(v3,{base10:()=>bR});var bR=rs({prefix:"9",name:"base10",alphabet:"0123456789"});var S3={};V(S3,{base16:()=>xR,base16upper:()=>ER});var xR=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),ER=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var A3={};V(A3,{base2:()=>vR});var vR=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var I3={};V(I3,{base256emoji:()=>CR});var zb=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}"),SR=zb.reduce((r,e,t)=>(r[t]=e,r),[]),AR=zb.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function IR(r){return r.reduce((e,t)=>(e+=SR[t],e),"")}function TR(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=AR[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var CR=Aa({prefix:"\u{1F680}",name:"base256emoji",encode:IR,decode:TR});var T3={};V(T3,{base8:()=>kR});var kR=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var C3={};V(C3,{identity:()=>_R});var _R=Aa({prefix:"\0",name:"identity",encode:r=>xb(wr(r)),decode:r=>wr(bb(r))});var Sh={};V(Sh,{code:()=>RR,decode:()=>OR,encode:()=>NR,name:()=>DR});var PR=new TextEncoder,LR=new TextDecoder,DR="json",RR=512;function NR(r){return PR.encode(JSON.stringify(r))}function OR(r){return JSON.parse(LR.decode(r))}var fi={};V(fi,{code:()=>po,decode:()=>UR,encode:()=>MR,name:()=>BR});var BR="raw",po=85;function MR(r){return wr(r)}function UR(r){return wr(r)}var _3={};V(_3,{sha256:()=>He,sha512:()=>k3});function Wb(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var He=jl({name:"sha2-256",code:18,encode:Wb("SHA-256")}),k3=jl({name:"sha2-512",code:19,encode:Wb("SHA-512")});var hi={...C3,...A3,...T3,...v3,...S3,...n3,...o3,...s3,...u3,...I3},GQ={..._3,...d3};function jb(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Gb=jb("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),P3=jb("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=st(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),FR={utf8:Gb,"utf-8":Gb,hex:hi.base16,latin1:P3,ascii:P3,binary:P3,...hi},Ah=FR;function O(r,e="utf8"){let t=Ah[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,o=e;return function(i){if(i<1||i>t)return st(i);o+i>e&&(n=st(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var pi=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function D3(){}var N3=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},$R=L3();function KR(r){return globalThis.Buffer!=null?st(r):$R(r)}var tu=class{len;head;tail;states;constructor(){this.len=0,this.head=new pi(D3,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new pi(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new O3((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(Ih,10,Pr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Pr.fromBigInt(e);return this._push(Ih,t.length(),t)}uint64Number(e){return this._push(ka,we(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=Pr.fromBigInt(e).zzEncode();return this._push(Ih,t.length(),t)}sint64Number(e){let t=Pr.fromNumber(e).zzEncode();return this._push(Ih,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(R3,1,e?1:0)}fixed32(e){return this._push(eu,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pr.fromBigInt(e);return this._push(eu,4,t.lo)._push(eu,4,t.hi)}fixed64Number(e){let t=Pr.fromNumber(e);return this._push(eu,4,t.lo)._push(eu,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(Mb,4,e)}double(e){return this._push(Fb,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(R3,1,0):this.uint32(t)._push(HR,t,e)}string(e){let t=Vb(e);return t!==0?this.uint32(t)._push(x3,t,e):this._push(R3,1,0)}fork(){return this.states=new N3(this),this.head=this.tail=new pi(D3,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 pi(D3,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=KR(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function R3(r,e,t){e[t]=r&255}function VR(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var O3=class extends pi{next;constructor(e,t){super(VR,e,t),this.next=void 0}};function Ih(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 eu(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 HR(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(tu.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(qR,e,r),this},tu.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zR,e,r),this});function qR(r,e,t){e.set(r,t)}function zR(r,e,t){r.length<40?x3(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(O(r),t)}function B3(){return new tu}function se(r,e){let t=B3();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ie(r,e,t){let n=Zl(r);yield*e.stream(n,void 0,"$",t)}var Th={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ch(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function et(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ch("enum",Th.VARINT,t,n,o)}function ae(r,e,t){return Ch("message",Th.LENGTH_DELIMITED,r,e,t)}var he=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ru=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var kh;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(kh||(kh={}));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=()=>et(M3)})(kh||(kh={}));var br;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),i.int32(s.Type)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=s.int32();break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:s.int32()};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(br||(br={}));var ar;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),i.int32(s.Type)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=s.int32();break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:s.int32()};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(ar||(ar={}));var WR=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),GR=Uint8Array.from([6,5,43,129,4,0,34]),jR=Uint8Array.from([6,5,43,129,4,0,35]),Yb={ext:!0,kty:"EC",crv:"P-256"},Xb={ext:!0,kty:"EC",crv:"P-384"},Qb={ext:!0,kty:"EC",crv:"P-521"},_a=32,Pa=48,La=66,nu=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return Ze.digest(this.toProtobuf())}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return br.encode({Type:this.code,Data:JR(this.jwk)})}async verify(e,t,n){let o=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,ee(t),ee(e));return n?.signal?.throwIfAborted(),s}},_h=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return ar.encode({Type:this.code,Data:ZR(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"]),o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,ee(e));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}},U3=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"]),o=await crypto.subtle.exportKey("jwk",n.privateKey),s=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new _h(o,new nu(s))}async publicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let o=QR(n.Data);return new nu(o)}async privateKeyFromProtobuf(e,t){let n=ar.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=XR(n.Data),s=YR(o);return t?.signal?.throwIfAborted(),new _h(o,new nu(s))}};function F3(){return new U3}function YR(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function XR(r){let e=ln(r),t=e[1],n=ne.baseEncode(t),o=e[2][1][0],s=1,i,a;if(t.byteLength===_a)return i=ne.baseEncode(o.subarray(s,s+_a)),a=ne.baseEncode(o.subarray(s+_a)),{...Yb,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===Pa)return i=ne.baseEncode(o.subarray(s,s+Pa)),a=ne.baseEncode(o.subarray(s+Pa)),{...Xb,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===La)return i=ne.baseEncode(o.subarray(s,s+La)),a=ne.baseEncode(o.subarray(s+La)),{...Qb,key_ops:["sign"],d:n,x:i,y:a};throw new Ve(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function QR(r){let t=ln(r)[1][1][0],n=1,o,s;if(t.byteLength===_a*2+1)return o=ne.baseEncode(t.subarray(n,n+_a)),s=ne.baseEncode(t.subarray(n+_a)),{...Yb,key_ops:["verify"],x:o,y:s};if(t.byteLength===Pa*2+1)return o=ne.baseEncode(t.subarray(n,n+Pa)),s=ne.baseEncode(t.subarray(n+Pa)),{...Xb,key_ops:["verify"],x:o,y:s};if(t.byteLength===La*2+1)return o=ne.baseEncode(t.subarray(n,n+La)),s=ne.baseEncode(t.subarray(n+La)),{...Qb,key_ops:["verify"],x:o,y:s};throw new Ve(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function JR(r){return un([ir(Uint8Array.from([1])),un([Jb(r.crv)],160),un([Jl(new Y(Uint8Array.from([4]),ne.baseDecode(r.x??""),ne.baseDecode(r.y??"")))],161)]).subarray()}function ZR(r){return un([ir(Uint8Array.from([1])),Bb(ne.baseDecode(r.d??"")),un([Jb(r.crv)],160),un([Jl(new Y(Uint8Array.from([4]),ne.baseDecode(r.x??""),ne.baseDecode(r.y??"")))],161)]).subarray()}function Jb(r){if(r==="P-256")return WR;if(r==="P-384")return GR;if(r==="P-521")return jR;throw new Ve(`Invalid curve ${r}`)}var eN=32,ou=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return Ze.digest(this.toProtobuf())}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return br.encode({Type:this.code,Data:ne.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let o=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),s=await crypto.subtle.verify({name:"Ed25519"},o,ee(t),ee(e));return n?.signal?.throwIfAborted(),s}},Ph=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return ar.encode({Type:this.code,Data:Ke([ne.baseDecode(this.jwk.d??""),ne.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"]),o=await crypto.subtle.sign({name:"Ed25519"},n,ee(e));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}},$3=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),o=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Ph(n,new ou(o))}async publicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let o=oN(n.Data);return new ou(o)}async privateKeyFromProtobuf(e,t){let n=ar.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=await tN(n.Data,t),s=nN(o);return new Ph(o,new ou(s))}};function K3(){return new $3}async function tN(r,e){let t=r.subarray(0,eN),n=rN(t),o=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),s=await crypto.subtle.exportKey("jwk",o);return e?.signal?.throwIfAborted(),s}var Zb=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function rN(r){return Ke([Zb,Uint8Array.from([r.byteLength]),r],Zb.byteLength+1+r.byteLength)}function nN(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function oN(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:ne.baseEncode(r)}}var q3=8192,su=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(t9(e)>q3)throw new Ve("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return K.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(or)}toProtobuf(){return uN(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let o=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),s=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,ee(t),ee(e));return n?.signal?.throwIfAborted(),s}},Lh=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(t9(e)>q3)throw new Ve("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return dN(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"]),o=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,ee(e));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}},H3=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>q3)throw new Ve("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"]),o=await crypto.subtle.exportKey("jwk",n.privateKey),s=await crypto.subtle.exportKey("jwk",n.publicKey),i=await V3(o);return e?.signal?.throwIfAborted(),new Lh(o,new su(s,i))}async publicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=cN(n.Data),s=await V3(o);return t?.signal?.throwIfAborted(),new su(o,s)}async privateKeyFromProtobuf(e,t){let n=ar.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=ln(n.Data),s=sN(o),i=lN(s),a=await V3(i);return t?.signal?.throwIfAborted(),new Lh(s,new su(i,a))}};function iu(){return new H3}function sN(r){return{alg:"RS256",kty:"RSA",n:ne.baseEncode(r[1]),e:ne.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:ne.baseEncode(r[3]),p:ne.baseEncode(r[4]),q:ne.baseEncode(r[5]),dp:ne.baseEncode(r[6]),dq:ne.baseEncode(r[7]),qi:ne.baseEncode(r[8])}}function iN(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 Ve("JWK was missing components");return un([ir(Uint8Array.from([0])),ir(ne.baseDecode(r.n)),ir(ne.baseDecode(r.e)),ir(ne.baseDecode(r.d)),ir(ne.baseDecode(r.p)),ir(ne.baseDecode(r.q)),ir(ne.baseDecode(r.dp)),ir(ne.baseDecode(r.dq)),ir(ne.baseDecode(r.qi))]).subarray()}var aN=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function e9(r){if(r.n==null||r.e==null)throw new Ve("JWK public key was missing components");return un([aN,Jl(un([ir(ne.baseDecode(r.n)),ir(ne.baseDecode(r.e))]))]).subarray()}function cN(r){let e=ln(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=ln(e[1]);return{kty:"RSA",n:ne.baseEncode(t[0]),e:ne.baseEncode(t[1])}}function lN(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function t9(r){if(r.kty!=="RSA")throw new Ve("Invalid key type");if(r.n==null)throw new Ve("Invalid key modulus");return ne.baseDecode(r.n).length*8}async function V3(r){let e=br.encode({Type:0,Data:e9(r)});return He.digest(e)}function uN(r,e){return br.encode({Type:r,Data:e9(e)})}function dN(r,e){return ar.encode({Type:r,Data:iN(e)})}function z3(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.verify=="function"}function r9(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.sign=="function"&&z3(r.publicKey)}var W3=1,G3=5,j3=100;var au=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},os=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},cu=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},lu=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},Y3=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}},uu=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"};var X3={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},n9={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},o9=new globalThis.TextEncoder;function fN(r,e){let t=X3[e],n=n9[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function hN(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=X3[e],o=n9[e],s=r;for(;s.length>0;){let i=o9.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Q3(r,{size:e=32,utf8Buffer:t}={}){if(!X3[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 hN(r,e,t);r=o9.encode(r)}return fN(r,e)}var du={hash:r=>Number(Q3(r,{size:32})),hashV:(r,e)=>pN(du.hash(r,e))};function pN(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),O(e,"base16")}var J3=64,fn=class{fp;h;seed;constructor(e,t,n,o=2){if(o>J3)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=me(o);for(let a=0;a<i.length;a++)i[a]=s[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?te(this.fp,e.fp):!1}};function mi(r,e){return Math.floor(Math.random()*(e-r))+r}var gi=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof fn))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof fn))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 fn))throw new TypeError("Invalid Fingerprint");let t=mi(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof fn))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var mN=500,fu=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??du,this.seed=e.seed??mi(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=O(e));let t=new fn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new gi(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new gi(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[mi(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new gi(this.bucketSize));for(let a=0;a<mN;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 gi(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=O(e));let t=new fn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=O(e));let t=new fn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},gN={1:.5,2:.84,4:.95,8:.98};function yN(r=.001){return r>.002?2:r>1e-5?4:8}function s9(r,e=.001){let t=yN(e),n=gN[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),J3);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Dh=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??du,this.seed=e.seed??mi(0,Math.pow(2,10)),this.filterSeries=[new fu({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=O(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new fu({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=O(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=O(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 Nt(r,e=.001,t){return new Dh({...s9(r,e),...t??{}})}function Z3(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 ce(r){let e=Z3(r);if(e==null)throw new A(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Rh=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var i9=45,wN=15,Da=new Rh;function Nh(r){if(!(r.length>wN))return Da.new(r).parseWith(()=>Da.readIPv4Addr())}function Oh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>i9))return Da.new(r).parseWith(()=>Da.readIPv6Addr())}function Ra(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>i9)return;let t=Da.new(r).parseWith(()=>Da.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 a9(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function c9(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function e4(r){switch(r.length){case yi:return r.join(".");case wi:{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 l9(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function u9(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var yi=4,wi=16,jZ=parseInt("0xFFFF",16),bN=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hu(r,e){e.length===wi&&r.length===yi&&a9(e,0,11)&&(e=e.slice(12)),e.length===yi&&r.length===wi&&c9(r,bN,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function d9(r,e){if(typeof e=="string"&&(e=Ra(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 t4(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=yi,o=Nh(e);if(o==null&&(n=wi,o=Oh(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=r4(s,8*n);return{network:hu(o,i),mask:i}}function r4(r,e){if(e!==8*yi&&e!==8*wi)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var bi=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=t4(e));else{let n=Ra(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Ra(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=r4(o,8*n.length);this.network=hu(n,this.mask)}}contains(e){return d9({network:this.network,mask:this.mask},e)}toString(){let e=l9(this.mask),t=e!==-1?String(e):u9(this.mask);return e4(this.network)+"/"+t}};function f9(r,e){return new bi(r).contains(e)}function Bh(r){try{let e=ce(r);return e.type==="ip6"?f9("2000::/3",e.host):!1}catch{return!1}}function h9(r){try{let e=ce(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 p9(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function pu(r){try{let e=ce(r);switch(e.type){case"ip4":case"ip6":return p9(e.host);default:return!1}}catch{return!1}}function Ot(r){return Z3(r)!==null}function hn(r){return!!Nh(r)}function Mh(r){return!!Oh(r)}var w9=ti(y9(),1),TN=["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"],CN=TN.map(r=>new w9.Netmask(r));function l4(r){for(let e of CN)if(e.contains(r))return!0;return!1}function kN(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function _N(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return l4(o)}function PN(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function LN(r){let e=r.split(":"),t=e[e.length-1];return l4(t)}function DN(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 Ma(r){if(hn(r))return l4(r);if(kN(r))return _N(r);if(PN(r))return LN(r);if(Mh(r))return DN(r)}function it(r){try{let e=ce(r);switch(e.type){case"ip4":case"ip6":return Ma(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function is(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 pn(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=st(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return xh(t)}function M(r,e="utf8"){let t=Ah[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Bt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},mo=class extends Error{static name="ValidationError";name="ValidationError"},Fh=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},$h=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function d4(r){return e=>M(e,r)}function f4(r){return e=>O(e,r)}function Ua(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ei(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function b9(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=O(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ei(n);return Ke([t,o],t.length+o.length)}function x9(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=pt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ei(n);return Ke([t,o],t.length+o.length)}function h4(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=M(e,"base32"),o=Ua(t);return`${n}:${o}`}var p4=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Bt("Invalid byte value in IP address");e[n]=o}),e},E9=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=hn(t[n]),i;s&&(i=p4(t[n]),t[n]=M(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,M(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Bt("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},v9=function(r){if(r.byteLength!==4)throw new Bt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},S9=function(r){if(r.byteLength!==16)throw new Bt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.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 Bt(`Invalid IPv6 address "${t}"`)}};function A9(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Bt(`Invalid IPv6 address "${r}"`)}}var u4=Object.values(hi).map(r=>r.decoder),RN=(function(){let r=u4[0].or(u4[1]);return u4.slice(2).forEach(e=>r=r.or(e)),r})();function I9(r){return RN.decode(r)}function T9(r){return e=>r.encoder.encode(e)}function NN(r){if(parseInt(r).toString()!==r)throw new mo("Value must be an integer")}function ON(r){if(r<0)throw new mo("Value must be a positive integer, or zero")}function BN(r){return e=>{if(e>r)throw new mo(`Value must be smaller than or equal to ${r}`)}}function MN(...r){return e=>{for(let t of r)t(e)}}var mu=MN(NN,ON,BN(65535));var kt=-1,m4=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 $h(`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)}))}},yo=new m4,QN=[{code:4,name:"ip4",size:32,valueToBytes:p4,bytesToValue:v9,validate:r=>{if(!hn(r))throw new mo(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:273,name:"udp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:33,name:"dccp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:41,name:"ip6",size:128,valueToBytes:E9,bytesToValue:S9,stringToValue:A9,validate:r=>{if(!Mh(r))throw new mo(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:kt},{code:43,name:"ipcidr",size:8,bytesToValue:d4("base10"),valueToBytes:f4("base10")},{code:53,name:"dns",size:kt},{code:54,name:"dns4",size:kt},{code:55,name:"dns6",size:kt},{code:56,name:"dnsaddr",size:kt},{code:132,name:"sctp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:kt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:kt,bytesToValue:d4("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?f4("base58btc")(r):K.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:h4,valueToBytes:b9},{code:445,name:"onion3",size:296,bytesToValue:h4,valueToBytes:x9},{code:446,name:"garlic64",size:kt},{code:447,name:"garlic32",size:kt},{code:448,name:"tls"},{code:449,name:"sni",size:kt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:kt,bytesToValue:T9(ne),valueToBytes:I9},{code:480,name:"http"},{code:481,name:"http-path",size:kt,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:kt}];QN.forEach(r=>{yo.addProtocol(r)});function C9(r){let e=[],t=0;for(;t<r.length;){let n=_r(r,t),o=yo.getProtocol(n),s=we(n),i=JN(o,r,t+s),a=0;i>0&&o.size===kt&&(a=we(i));let c=s+a+i,l={code:n,name:o.name,bytes:ee(r.subarray(t,t+c))};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??M(d)}e.push(l),t+=c}return e}function k9(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=yo.getProtocol(n.code),s=we(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??O(n.value),a=i.byteLength,o.size===kt&&(c=we(a)));let l=new Uint8Array(s+c+a),u=0;ka(n.code,l,u),u+=s,i!=null&&(o.size===kt&&(ka(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 _9(r){if(r.charAt(0)!=="/")throw new Bt('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=yo.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Bt(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Bt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Bt("Incomplete multiaddr");return e}function P9(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=yo.getProtocol(e.code);if(t==null)throw new Bt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function JN(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:_r(e,t)}var ZN=Symbol.for("nodejs.util.inspect.custom"),A4=Symbol.for("@multiformats/multiaddr");function eO(r){if(r==null&&(r="/"),jr(r))return r.getComponents();if(r instanceof Uint8Array)return C9(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),_9(r);if(Array.isArray(r))return r;throw new Bt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var zh=class r{[A4]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=eO(e),t.validate!==!1&&tO(this)}get bytes(){return this.#r==null&&(this.#r=k9(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=P9(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Fh(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return te(this.bytes,e.bytes)}[ZN](){return`Multiaddr(${this.toString()})`}};function tO(r){r.getComponents().forEach(e=>{let t=yo.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function jr(r){return!!r?.[A4]}function G(r){return new zh(r)}var De=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),re=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),L9=r=>({match:e=>r.match(e)===!1?e:!1}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Yt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),Se=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Re(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var rO=re(421),D9=Re(rO),Gh=re(54),jh=re(55),Yh=re(56),T4=re(53),Mte=Re(Gh,be(re(421))),Ute=Re(jh,be(re(421))),Fte=Re(Yh,be(re(421))),Xh=Re(Yt(T4,Yh,Gh,jh),be(re(421))),R9=Se(re(4),be(re(43))),N9=Se(be(re(42)),re(41),be(re(43))),C4=Yt(R9,N9),Va=Yt(C4,T4,Gh,jh,Yh),O9=Re(Yt(C4,Se(Yt(T4,Yh,Gh,jh),be(re(421))))),k4=Re(R9),_4=Re(N9),B9=Re(C4),P4=Se(Va,re(6)),Eu=Se(Va,re(273)),Si=Re(Se(P4,be(re(421)))),$te=Re(Eu),L4=Se(Eu,De(460),be(re(421))),Qh=Se(Eu,De(461),be(re(421))),nO=Yt(L4,Qh),Kte=Re(L4),M9=Re(Qh),I4=Yt(Va,P4,Eu,L4,Qh),U9=Yt(Se(I4,De(477),be(re(421)))),wo=Re(U9),F9=Yt(Se(I4,De(478),be(re(421))),Se(I4,De(448),be(re(449)),De(477),be(re(421)))),Ai=Re(F9),$9=Se(Eu,De(280),be(re(466)),be(re(466)),be(re(421))),vu=Re($9),K9=Se(Qh,De(465),be(re(466)),be(re(466)),be(re(421))),D4=Re(K9),Wh=Yt(U9,F9,Se(P4,be(re(421))),Se(nO,be(re(421))),Se(Va,be(re(421))),$9,K9,re(421)),Ha=Re(Wh),oO=Se(be(Wh),De(290),L9(De(281)),be(re(421))),_t=Re(oO),sO=Yt(Se(Wh,De(290),De(281),be(re(421))),Se(Wh,De(281),be(re(421))),Se(De(281),be(re(421)))),Su=Re(sO),iO=Se(Va,Yt(Se(re(6,"80")),Se(re(6),De(480)),De(480)),be(re(481)),be(re(421))),V9=Re(iO),aO=Se(Va,Yt(Se(re(6,"443")),Se(re(6,"443"),De(480)),Se(re(6),De(443)),Se(re(6),De(448),De(480)),Se(De(448),De(480)),De(448),De(443)),be(re(481)),be(re(421))),H9=Re(aO),cO=Yt(Se(re(777),be(re(421)))),Vte=Re(cO),lO=Yt(Se(re(400),be(re(421)))),Hte=Re(lO);function q9(r,e){let t=Si.exactMatch(r),n=Si.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=Ai.exactMatch(r),s=Ai.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=wo.exactMatch(r),a=wo.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=Su.exactMatch(r),l=Su.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=vu.exactMatch(r),d=vu.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=D4.exactMatch(r),h=D4.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function z9(r,e){let t=pu(r),n=pu(e);return t&&!n?1:!t&&n?-1:0}function W9(r,e){let t=it(r),n=it(e);return t&&!n?1:!t&&n?-1:0}function G9(r,e){let t=_t.exactMatch(r),n=_t.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function qe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Jh=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}},qa=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Jh(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 Jh(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 R4=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Mt(r={}){return uO(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 uO(r,e){e=e??{};let t=e.onEnd,n=new qa,o,s,i,a=qe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,m)=>{s=w=>{s=null,n.push(w);try{g(r(n))}catch(x){m(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=qe()})}},l=g=>s!=null?s(g):(n.push(g),o),u=g=>(n=new qa,s!=null?s({error:g}):(n.push({error:g}),o)),d=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>i?o:(i=!0,g!=null?u(g):l({done:!0})),h=()=>(n=new qa,f(),{done:!0}),p=g=>(f(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async g=>{let m=g?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let w,x;m!=null&&(w=new Promise((E,S)=>{x=()=>{S(new R4)},m.addEventListener("abort",x)}));try{await Promise.race([a.promise,w])}finally{x!=null&&m!=null&&m?.removeEventListener("abort",x)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(g){return y.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:g=>y.onEmpty(g)},o}var N4=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},j9=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function cr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={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(j9(i));return}if(i&&(c=()=>{f(j9(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new N4;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var dO=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 fO(r,e,t){let n,o=new Promise((s,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}=dO(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=cr(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Yr(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=fO(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function bo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Zh=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}},e1=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Ii=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},t1=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},r1=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function hO(r){return r.reason}async function Ue(r,e,t){if(e==null)return r;let n=t?.translateError??hO;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var n1=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=qe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new nr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function pO(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var o1=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=pO(),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 nr),this.cleanup())}async join(e){let t=new n1(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 Ue(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){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.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var mt=class extends le{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=bo(this.emitEmpty.bind(this),1),this.emitIdle=bo(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 e1;let n=new o1(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new nr)}),this.clear()}async onEmpty(e){this.size!==0&&await Yr(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Yr(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Yr(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=Mt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new nr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var mO=Math.pow(2,20)*4,cs=class extends le{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??mO,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new Y,this.writeBuffer=new Y,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(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new r1)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ue(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Mt(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Nn(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new mh(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Nn("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 Nn("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 Nn(`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 Nn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new xa;this.dispatchEvent(new gh(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new es))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;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 o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new Y(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}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}}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 ph(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Vl(`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 Vl(`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 ls=class extends cs{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 Yr(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 Yr(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function s1(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var us=class extends le{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 o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}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 Ue(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 an;let t=this.onCreateStream({...this.streamOptions,...e});return s1(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 t1(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ds=class extends cs{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 Yr(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 Yr(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var za=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var gO=1.2,yO=2,wO=5e3,bO=6e4,xO=5e3,yn=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??xO;this.success=new za(t),this.failure=new za(t),this.next=new za(t),this.failureMultiplier=e.failureMultiplier??yO,this.timeoutMultiplier=e.timeoutMultiplier??gO,this.minTimeout=e.minTimeout??wO,this.maxTimeout=e.maxTimeout??bO,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=de([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var O4=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=qe(),this.haveNext=qe()}[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=qe(),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=qe(),await Ue(this.readNext.promise,t?.signal,t)}};function Y9(){return new O4}function EO(r){return r[Symbol.asyncIterator]!=null}async function vO(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*SO(r){let e=new AbortController,t=Y9();vO(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*AO(r){for(let e of r)yield*e}function IO(...r){let e=[];for(let t of r)EO(t)||e.push(t);return e.length===r.length?AO(e):SO(r)}var lr=IO;function Wa(r,...e){if(r==null)throw new Error("Empty pipeline");if(B4(r)){let n=r;r=()=>n.source}else if(Q9(r)||X9(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&B4(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++)B4(t[n])&&(t[n]=CO(t[n]));return TO(...t)}var TO=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},X9=r=>r?.[Symbol.asyncIterator]!=null,Q9=r=>r?.[Symbol.iterator]!=null,B4=r=>r==null?!1:r.sink!=null&&r.source!=null,CO=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Mt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(X9(s))o=async function*(){yield*s,n.end()};else if(Q9(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return lr(n,o())}return r.source};var kO=4194304,i1=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Au=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},U4=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},F4=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function _O(r){return typeof r?.closeRead=="function"}function PO(r){return typeof r?.close=="function"}function M4(r){return _O(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:PO(r)?r.status!=="open":!1}function LO(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function a1(r,e){let t=e?.maxBufferSize??kO,n=new Y,o,s=!1;if(!LO(r))throw new A("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new i1("Stream was unwrapped");if(M4(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Ii(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ue(o.promise,u?.signal),M4(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let f=u?.bytes??n.byteLength;if(n.byteLength<f){if(M4(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new Ii(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(u)}let h=n.sublist(0,f);return n.consume(f),h},async write(u,d){if(s===!0)throw new i1("Stream was unwrapped");r.send(u)||await Yr(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function fs(r,e={}){let t=a1(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=we(e.maxDataLength));let n=e?.lengthDecoder??_r,o=e?.lengthEncoder??Gt;return{async read(i){let a=-1,c=new Y;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 Au("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new F4(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new U4(`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 Ii(`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 Ii(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function We(r,e){let t=fs(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var DO=1024*1024*4,RO=1024*1024*4,c1=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new Y,this.maxBufferSize=e.maxBufferSize??DO,this.maxDataLength=e.maxDataLength??RO,this.lengthDecoder=e.lengthDecoder??_r,this.encodingLength=e.encodingLength??we}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new A(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(t<0||t>this.maxDataLength)throw new Au("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var NO=["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 $4(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=OO(r);return t||"Object"}function OO(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(NO.includes(e))return e}var b=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}};b.uint=new b(0,"uint",!0);b.negint=new b(1,"negint",!0);b.bytes=new b(2,"bytes",!0);b.string=new b(3,"string",!0);b.array=new b(4,"array",!1);b.map=new b(5,"map",!1);b.tag=new b(6,"tag",!1);b.float=new b(7,"float",!0);b.false=new b(7,"false",!0);b.true=new b(7,"true",!0);b.null=new b(7,"null",!0);b.undefined=new b(7,"undefined",!0);b.break=new b(7,"break",!0);var B=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 Iu=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",BO=new TextEncoder;function l1(r){return Iu&&globalThis.Buffer.isBuffer(r)}function Ti(r){return r instanceof Uint8Array?l1(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var MO=24,UO=200,Ga=Iu?r=>r.length>=MO?globalThis.Buffer.from(r):J9(r):r=>r.length>=UO?BO.encode(r):J9(r),Fn=r=>Uint8Array.from(r),ex=Iu?(r,e,t)=>l1(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),tx=Iu?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Ti(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},rx=Iu?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function u1(r,e){if(l1(r)&&l1(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 J9(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var Z9=4096;function nx(r){let e=r.length;if(e<=Z9)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Z9));return t}var FO=256,Tu=class{constructor(e=FO){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=rx(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=ex(n,0,this.cursor)}else t=tx(this.chunks,this.cursor);return e&&this.reset(),t}},d1=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var W="CBOR decode error:",$n="CBOR encode error:",Cu=[];Cu[23]=1;Cu[24]=2;Cu[25]=3;Cu[26]=5;Cu[27]=9;function xo(r,e,t){if(r.length-e<t)throw new Error(`${W} not enough data for type`)}var Pt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Lr(r,e,t){xo(r,e,1);let n=r[e];if(t.strict===!0&&n<Pt[0])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function Dr(r,e,t){xo(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Pt[1])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function Rr(r,e,t){xo(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Pt[2])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function Nr(r,e,t){xo(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<Pt[3])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${W} integers outside of the safe integer range are not supported`)}function ox(r,e,t,n){return new B(b.uint,Lr(r,e+1,n),2)}function sx(r,e,t,n){return new B(b.uint,Dr(r,e+1,n),3)}function ix(r,e,t,n){return new B(b.uint,Rr(r,e+1,n),5)}function ax(r,e,t,n){return new B(b.uint,Nr(r,e+1,n),9)}function Xr(r,e){return Ge(r,0,e.value)}function Ge(r,e,t){if(t<Pt[0]){let n=Number(t);r.push([e|n])}else if(t<Pt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Pt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Pt[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<Pt[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${W} encountered BigInt larger than allowable range`)}}Xr.encodedSize=function(e){return Ge.encodedSize(e.value)};Ge.encodedSize=function(e){return e<Pt[0]?1:e<Pt[1]?2:e<Pt[2]?3:e<Pt[3]?5:9};Xr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function cx(r,e,t,n){return new B(b.negint,-1-Lr(r,e+1,n),2)}function lx(r,e,t,n){return new B(b.negint,-1-Dr(r,e+1,n),3)}function ux(r,e,t,n){return new B(b.negint,-1-Rr(r,e+1,n),5)}var K4=BigInt(-1),dx=BigInt(1);function fx(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new B(b.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${W} integers outside of the safe integer range are not supported`);return new B(b.negint,K4-BigInt(o),9)}function f1(r,e){let t=e.value,n=typeof t=="bigint"?t*K4-dx:t*-1-1;Ge(r,e.type.majorEncoded,n)}f1.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*K4-dx:t*-1-1;return n<Pt[0]?1:n<Pt[1]?2:n<Pt[2]?3:n<Pt[3]?5:9};f1.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ku(r,e,t,n){xo(r,e,t+n);let o=r.slice(e+t,e+t+n);return new B(b.bytes,o,t+n)}function hx(r,e,t,n){return ku(r,e,1,t)}function px(r,e,t,n){return ku(r,e,2,Lr(r,e+1,n))}function mx(r,e,t,n){return ku(r,e,3,Dr(r,e+1,n))}function gx(r,e,t,n){return ku(r,e,5,Rr(r,e+1,n))}function yx(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer bytes lengths not supported`);return ku(r,e,9,o)}function h1(r){return r.encodedBytes===void 0&&(r.encodedBytes=b.equals(r.type,b.string)?Ga(r.value):r.value),r.encodedBytes}function ja(r,e){let t=h1(e);Ge(r,e.type.majorEncoded,t.length),r.push(t)}ja.encodedSize=function(e){let t=h1(e);return Ge.encodedSize(t.length)+t.length};ja.compareTokens=function(e,t){return KO(h1(e),h1(t))};function KO(r,e){return r.length<e.length?-1:r.length>e.length?1:u1(r,e)}var wx=new TextDecoder,HO=32;function qO(r,e,t){if(t-e<HO){let o="";for(let s=e;s<t;s++){let i=r[s];if(i&128)return wx.decode(r.subarray(e,t));o+=String.fromCharCode(i)}return o}return wx.decode(r.subarray(e,t))}function _u(r,e,t,n,o){let s=t+n;xo(r,e,s);let i=new B(b.string,qO(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=r.slice(e+t,e+s)),i}function bx(r,e,t,n){return _u(r,e,1,t,n)}function xx(r,e,t,n){return _u(r,e,2,Lr(r,e+1,n),n)}function Ex(r,e,t,n){return _u(r,e,3,Dr(r,e+1,n),n)}function vx(r,e,t,n){return _u(r,e,5,Rr(r,e+1,n),n)}function Sx(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer string lengths not supported`);return _u(r,e,9,o,n)}var Ax=ja;function Ya(r,e,t,n){return new B(b.array,n,t)}function Ix(r,e,t,n){return Ya(r,e,1,t)}function Tx(r,e,t,n){return Ya(r,e,2,Lr(r,e+1,n))}function Cx(r,e,t,n){return Ya(r,e,3,Dr(r,e+1,n))}function kx(r,e,t,n){return Ya(r,e,5,Rr(r,e+1,n))}function _x(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer array lengths not supported`);return Ya(r,e,9,o)}function Px(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Ya(r,e,1,1/0)}function p1(r,e){Ge(r,b.array.majorEncoded,e.value)}p1.compareTokens=Xr.compareTokens;p1.encodedSize=function(e){return Ge.encodedSize(e.value)};function Xa(r,e,t,n){return new B(b.map,n,t)}function Lx(r,e,t,n){return Xa(r,e,1,t)}function Dx(r,e,t,n){return Xa(r,e,2,Lr(r,e+1,n))}function Rx(r,e,t,n){return Xa(r,e,3,Dr(r,e+1,n))}function Nx(r,e,t,n){return Xa(r,e,5,Rr(r,e+1,n))}function Ox(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer map lengths not supported`);return Xa(r,e,9,o)}function Bx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Xa(r,e,1,1/0)}function m1(r,e){Ge(r,b.map.majorEncoded,e.value)}m1.compareTokens=Xr.compareTokens;m1.encodedSize=function(e){return Ge.encodedSize(e.value)};function Mx(r,e,t,n){return new B(b.tag,t,1)}function Ux(r,e,t,n){return new B(b.tag,Lr(r,e+1,n),2)}function Fx(r,e,t,n){return new B(b.tag,Dr(r,e+1,n),3)}function $x(r,e,t,n){return new B(b.tag,Rr(r,e+1,n),5)}function Kx(r,e,t,n){return new B(b.tag,Nr(r,e+1,n),9)}function g1(r,e){Ge(r,b.tag.majorEncoded,e.value)}g1.compareTokens=Xr.compareTokens;g1.encodedSize=function(e){return Ge.encodedSize(e.value)};var V4=20,H4=21,q4=22,z4=23;function Vx(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${W} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(b.null,null,1):new B(b.undefined,void 0,1)}function Hx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return new B(b.break,void 0,1)}function W4(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${W} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${W} Infinity values are not supported`)}return new B(b.float,r,e)}function qx(r,e,t,n){return W4(G4(r,e+1),3,n)}function zx(r,e,t,n){return W4(j4(r,e+1),5,n)}function Wx(r,e,t,n){return W4(Xx(r,e+1),9,n)}function Pu(r,e,t){let n=e.value;if(n===!1)r.push([b.float.majorEncoded|V4]);else if(n===!0)r.push([b.float.majorEncoded|H4]);else if(n===null)r.push([b.float.majorEncoded|q4]);else if(n===void 0)r.push([b.float.majorEncoded|z4]);else{let o,s=!1;(!t||t.float64!==!0)&&(jx(n),o=G4(wn,1),n===o||Number.isNaN(n)?(wn[0]=249,r.push(wn.slice(0,3)),s=!0):(Yx(n),o=j4(wn,1),n===o&&(wn[0]=250,r.push(wn.slice(0,5)),s=!0))),s||(YO(n),o=Xx(wn,1),wn[0]=251,r.push(wn.slice(0,9)))}}Pu.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){jx(n);let o=G4(wn,1);if(n===o||Number.isNaN(n))return 3;if(Yx(n),o=j4(wn,1),n===o)return 5}return 9};var Gx=new ArrayBuffer(9),Qr=new DataView(Gx,1),wn=new Uint8Array(Gx,0);function jx(r){if(r===1/0)Qr.setUint16(0,31744,!1);else if(r===-1/0)Qr.setUint16(0,64512,!1);else if(Number.isNaN(r))Qr.setUint16(0,32256,!1);else{Qr.setFloat32(0,r);let e=Qr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Qr.setUint16(0,31744,!1);else if(t===0)Qr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Qr.setUint16(0,0):o<-14?Qr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Qr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function G4(r,e){if(r.length-e<2)throw new Error(`${W} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function Yx(r){Qr.setFloat32(0,r,!1)}function j4(r,e){if(r.length-e<4)throw new Error(`${W} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function YO(r){Qr.setFloat64(0,r,!1)}function Xx(r,e){if(r.length-e<8)throw new Error(`${W} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Pu.compareTokens=Xr.compareTokens;function Ce(r,e,t){throw new Error(`${W} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function y1(r){return()=>{throw new Error(`${W} ${r}`)}}var q=[];for(let r=0;r<=23;r++)q[r]=Ce;q[24]=ox;q[25]=sx;q[26]=ix;q[27]=ax;q[28]=Ce;q[29]=Ce;q[30]=Ce;q[31]=Ce;for(let r=32;r<=55;r++)q[r]=Ce;q[56]=cx;q[57]=lx;q[58]=ux;q[59]=fx;q[60]=Ce;q[61]=Ce;q[62]=Ce;q[63]=Ce;for(let r=64;r<=87;r++)q[r]=hx;q[88]=px;q[89]=mx;q[90]=gx;q[91]=yx;q[92]=Ce;q[93]=Ce;q[94]=Ce;q[95]=y1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)q[r]=bx;q[120]=xx;q[121]=Ex;q[122]=vx;q[123]=Sx;q[124]=Ce;q[125]=Ce;q[126]=Ce;q[127]=y1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)q[r]=Ix;q[152]=Tx;q[153]=Cx;q[154]=kx;q[155]=_x;q[156]=Ce;q[157]=Ce;q[158]=Ce;q[159]=Px;for(let r=160;r<=183;r++)q[r]=Lx;q[184]=Dx;q[185]=Rx;q[186]=Nx;q[187]=Ox;q[188]=Ce;q[189]=Ce;q[190]=Ce;q[191]=Bx;for(let r=192;r<=215;r++)q[r]=Mx;q[216]=Ux;q[217]=Fx;q[218]=$x;q[219]=Kx;q[220]=Ce;q[221]=Ce;q[222]=Ce;q[223]=Ce;for(let r=224;r<=243;r++)q[r]=y1("simple values are not supported");q[244]=Ce;q[245]=Ce;q[246]=Ce;q[247]=Vx;q[248]=y1("simple values are not supported");q[249]=qx;q[250]=zx;q[251]=Wx;q[252]=Ce;q[253]=Ce;q[254]=Ce;q[255]=Hx;var bn=[];for(let r=0;r<24;r++)bn[r]=new B(b.uint,r,1);for(let r=-1;r>=-24;r--)bn[31-r]=new B(b.negint,r,1);bn[64]=new B(b.bytes,new Uint8Array(0),1);bn[96]=new B(b.string,"",1);bn[128]=new B(b.array,0,1);bn[160]=new B(b.map,0,1);bn[244]=new B(b.false,!1,1);bn[245]=new B(b.true,!0,1);bn[246]=new B(b.null,null,1);function Y4(r){switch(r.type){case b.false:return Fn([244]);case b.true:return Fn([245]);case b.null:return Fn([246]);case b.bytes:return r.value.length?void 0:Fn([64]);case b.string:return r.value===""?Fn([96]):void 0;case b.array:return r.value===0?Fn([128]):void 0;case b.map:return r.value===0?Fn([160]):void 0;case b.uint:return r.value<24?Fn([Number(r.value)]):void 0;case b.negint:if(r.value>=-24)return Fn([31-Number(r.value)])}}var QO={float64:!1,mapSorter:eB,quickEncodeToken:Y4},tE=Object.freeze({mapSorter:tB,quickEncodeToken:Y4});function JO(){let r=[];return r[b.uint.major]=Xr,r[b.negint.major]=f1,r[b.bytes.major]=ja,r[b.string.major]=Ax,r[b.array.major]=p1,r[b.map.major]=m1,r[b.tag.major]=g1,r[b.float.major]=Pu,r}var Ja=JO(),w1=new Tu,Du=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(`${$n} object contains circular references`);return new r(t,e)}},hs={null:new B(b.null,null),undefined:new B(b.undefined,void 0),true:new B(b.true,!0),false:new B(b.false,!1),emptyArray:new B(b.array,0),emptyMap:new B(b.map,0)},Kn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new B(b.float,r):r>=0?new B(b.uint,r):new B(b.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new B(b.uint,r):new B(b.negint,r)},Uint8Array(r,e,t,n){return new B(b.bytes,r)},string(r,e,t,n){return new B(b.string,r)},boolean(r,e,t,n){return r?hs.true:hs.false},null(r,e,t,n){return hs.null},undefined(r,e,t,n){return hs.undefined},ArrayBuffer(r,e,t,n){return new B(b.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new B(b.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[hs.emptyArray,new B(b.break)]:hs.emptyArray;n=Du.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Qa(i,t,n);return t.addBreakTokens?[new B(b.array,r.length),o,new B(b.break)]:[new B(b.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length,a;if(i){a=new Array(i),n=Du.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of s){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[Qa(u,t,n),Qa(d,t,n)])}l<i&&(a.length=l)}return a?.length?(ZO(a,t),t.addBreakTokens?[new B(b.map,a.length),a,new B(b.break)]:[new B(b.map,a.length),a]):t.addBreakTokens===!0?[hs.emptyMap,new B(b.break)]:hs.emptyMap},Tagged(r,e,t,n){return[new B(b.tag,r.tag),Qa(r.value,t,n)]}};Kn.Map=Kn.Object;Kn.Buffer=Kn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Kn[`${r}Array`]=Kn.DataView;function Qa(r,e={},t){let n=$4(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Kn[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=Kn[n];if(!s)throw new Error(`${$n} unsupported type: ${n}`);return s(r,n,e,t)}function ZO(r,e){e.mapSorter&&r.sort(e.mapSorter)}function eB(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=Ja[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function tB(r,e){if(r[0]instanceof B&&e[0]instanceof B){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Qx(t.value)),n._keyBytes||(n._keyBytes=Qx(n.value)),u1(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Qx(r){return b1(r,Ja,tE)}function Lu(r,e,t,n){if(Array.isArray(e))for(let o of e)Lu(r,o,t,n);else t[e.type.major](r,e,n)}var Jx=b.uint.majorEncoded,Zx=b.negint.majorEncoded,rB=b.bytes.majorEncoded,nB=b.string.majorEncoded,eE=b.array.majorEncoded,oB=b.float.majorEncoded|V4,sB=b.float.majorEncoded|H4,iB=b.float.majorEncoded|q4,aB=b.float.majorEncoded|z4,cB=BigInt(-1),lB=BigInt(1);function uB(r){return r.addBreakTokens!==!0}function rE(r,e,t,n){let o=$4(e),s=t.typeEncoders&&t.typeEncoders[o];if(s){let i=s(e,o,t,n);if(i!=null){Lu(r,i,Ja,t);return}}switch(o){case"null":r.push([iB]);return;case"undefined":r.push([aB]);return;case"boolean":r.push([e?sB:oB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Pu(r,new B(b.float,e),t):e>=0?Ge(r,Jx,e):Ge(r,Zx,e*-1-1);return;case"bigint":e>=BigInt(0)?Ge(r,Jx,e):Ge(r,Zx,e*cB-lB);return;case"string":{let i=Ga(e);Ge(r,nB,i.length),r.push(i);return}case"Uint8Array":Ge(r,rB,e.length),r.push(e);return;case"Array":if(!e.length){r.push([eE]);return}n=Du.createCheck(n,e),Ge(r,eE,e.length);for(let i of e)rE(r,i,t,n);return;case"Object":case"Map":{let i=Kn.Object(e,o,t,n);Lu(r,i,Ja,t)}return;default:{let i=Kn[o];if(!i)throw new Error(`${$n} unsupported type: ${o}`);let a=i(e,o,t,n);Lu(r,a,Ja,t)}}}function b1(r,e,t,n){let o=n instanceof Uint8Array,s=o?new d1(n):w1,i=Qa(r,t);if(!Array.isArray(i)&&t.quickEncodeToken){let a=t.quickEncodeToken(i);if(a)return o?(s.push(a),s.toBytes()):a;let c=e[i.type.major];if(c.encodedSize){let l=c.encodedSize(i,t);if(o||(s=new Tu(l)),c(s,i,t),s.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${i} was wrong`);return o?s.toBytes():Ti(s.chunks[0])}}return s.reset(),Lu(s,i,e,t),s.toBytes(!0)}function ki(r,e){return e=Object.assign({},QO,e),uB(e)?(w1.reset(),rE(w1,r,e,void 0),w1.toBytes(!0)):b1(r,Ja,e)}var dB={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},x1=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=bn[e];if(t===void 0){let n=q[e];if(!n)throw new Error(`${W} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},ps=Symbol.for("DONE"),Za=Symbol.for("BREAK");function fB(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=ms(e,t);if(s===Za){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed array`)}if(s===ps)throw new Error(`${W} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function hB(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,s=n?void 0:{},i=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=ms(e,t);if(c===Za){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(c===ps)throw new Error(`${W} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${W} non-string keys not supported (got ${typeof c})`);if(o&&(n&&i.has(c)||!n&&Object.hasOwn(s,c)))throw new Error(`${W} found repeat map key "${c}"`);let l=ms(e,t);if(l===ps)throw new Error(`${W} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?i.set(c,l):s[c]=l}return n?i:s}function*pB(r,e,t){for(let n=0;n<r.value;n++){let o=ms(e,t);if(o===Za){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(o===ps)throw new Error(`${W} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let s=ms(e,t);if(s===ps)throw new Error(`${W} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,s]}}function mB(r,e){let t=!1,n=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=ms(r,e);if(o===ps)throw new Error(`${W} tag content missing`);if(o===Za)throw new Error(`${W} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=r.next();if(!b.equals(o.type,b.map))throw new Error(`${W} entries() requires map content, got ${o.type.name}`);let s=[];for(let i of pB(o,r,e))s.push(i);return s},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ms(r,e){if(r.done())return ps;let t=r.next();if(b.equals(t.type,b.break))return Za;if(t.type.terminal)return t.value;if(b.equals(t.type,b.array))return fB(t,r,e);if(b.equals(t.type,b.map))return hB(t,r,e);if(b.equals(t.type,b.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=mB(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${W} tag decoder must call decode() or entries()`);return o}throw new Error(`${W} tag not supported (${t.value})`)}throw new Error("unsupported")}function X4(r,e){if(!(r instanceof Uint8Array))throw new Error(`${W} data to decode must be a Uint8Array`);e=Object.assign({},dB,e);let t=Ti(r),n=e.tokenizer||new x1(t,e),o=ms(n,e);if(o===ps)throw new Error(`${W} did not find any content to decode`);if(o===Za)throw new Error(`${W} got unexpected break`);return[o,r.subarray(n.pos())]}function xn(r,e){let[t,n]=X4(r,e);if(n.length>0)throw new Error(`${W} too many terminals, data makes no sense`);return t}var E1=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(E1.prototype,Symbol.toStringTag,{value:"Tagged"});var v1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ec=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},S1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Ru=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function A1(r){return r[Symbol.asyncIterator]!=null}function oE(r,e){if(r.byteLength>e)throw new ec("Message length too long")}var T1=r=>{let e=we(r),t=st(e);return Gt(r,t),T1.bytes=e,t};T1.bytes=0;function Eo(r,e){e=e??{};let t=e.lengthEncoder??T1,n=e?.maxDataLength??4194304;function*o(s){oE(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return A1(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Eo.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??T1,n=e?.maxDataLength??4194304;return oE(r,n),new Y(t(r.byteLength),r)};var _i;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_i||(_i={}));var Q4=r=>{let e=_r(r);return Q4.bytes=we(e),e};Q4.bytes=0;function Pi(r,e){let t=new Y,n=_i.LENGTH,o=-1,s=e?.lengthDecoder??Q4,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===_i.LENGTH)try{if(o=s(t),o<0)throw new v1("Invalid message length");if(o>a)throw new ec("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=_i.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new S1("Message length length too long");break}throw l}if(n===_i.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=_i.LENGTH}}}return A1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Ru("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Ru("Unexpected end of input")})()}Pi.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Pi(n,{...e??{},onLength:s=>{t=s}})};function C1(r,e){if(typeof r=="string")return yB(r);if(typeof r=="number")return xB(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function yB(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,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function wB(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 bB(r){let e=Math.abs(r);return e>=315576e5?Li(r,e,315576e5,"year"):e>=26298e5?Li(r,e,26298e5,"month"):e>=6048e5?Li(r,e,6048e5,"week"):e>=864e5?Li(r,e,864e5,"day"):e>=36e5?Li(r,e,36e5,"hour"):e>=6e4?Li(r,e,6e4,"minute"):e>=1e3?Li(r,e,1e3,"second"):`${r} ms`}function xB(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?bB(r):wB(r)}function Li(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function J4(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=C1,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,y;function g(...m){if(!g.enabled)return;let w=g,x=Number(new Date),E=x-(f||x);w.diff=E,w.prev=f,w.curr=x,f=x,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let S=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(I,C)=>{if(I==="%%")return"%";S++;let U=t.formatters[C];if(typeof U=="function"){let j=m[S];I=U.call(w,j),m.splice(S,1),S--}return I}),t.formatArgs.call(w,m),d?.onLog!=null&&d.onLog(...m),(w.log||t.log).apply(w,m)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:m=>{h=m}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){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 k1=CB(),EB=["#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 vB(){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 SB(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+C1(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var AB=console.debug??console.log??(()=>{});function IB(r){try{r?k1?.setItem("debug",r):k1?.removeItem("debug")}catch{}}function TB(){let r;try{r=k1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function CB(){try{return localStorage}catch{}}function kB(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var iE=J4({formatArgs:SB,save:IB,load:TB,useColors:vB,setupFormatters:kB,colors:EB,storage:k1,log:AB});var je=iE;je.formatters.b=r=>r==null?"undefined":ge.baseEncode(r);je.formatters.t=r=>r==null?"undefined":pt.baseEncode(r);je.formatters.m=r=>r==null?"undefined":$e.baseEncode(r);je.formatters.p=r=>r==null?"undefined":r.toString();je.formatters.c=r=>r==null?"undefined":r.toString();je.formatters.k=r=>r==null?"undefined":r.toString();je.formatters.a=r=>r==null?"undefined":r.toString();function aE(r,e=""){let t=cE(r.message),n=cE(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
2
|
+
"use strict";var Helia=(()=>{var nD=Object.create;var ch=Object.defineProperty;var oD=Object.getOwnPropertyDescriptor;var sD=Object.getOwnPropertyNames;var iD=Object.getPrototypeOf,aD=Object.prototype.hasOwnProperty;var sn=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},V=(r,e)=>{for(var t in e)ch(r,t,{get:e[t],enumerable:!0})},mb=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sD(e))!aD.call(r,o)&&o!==t&&ch(r,o,{get:()=>e[o],enumerable:!(n=oD(e,o))||n.enumerable});return r};var ti=(r,e,t)=>(t=r!=null?nD(iD(r)):{},mb(e||!r||!r.__esModule?ch(t,"default",{value:r,enumerable:!0}):t,r)),cD=r=>mb(ch({},"__esModule",{value:!0}),r);var o4=sn(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.Netmask4Impl=void 0;Oa.ip2long=Na;Oa.long2ip=Mn;function Mn(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var xN=48,EN=97,vN=65;function SN(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-xN)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-EN)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-vN)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function Na(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=SN(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var n4=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Na(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Na(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=Mn(this.netLong),this.mask=Mn(this.maskLong),this.hostmask=Mn(~this.maskLong),this.first=this.bitmask<=30?Mn(this.netLong+1):this.base,this.last=this.bitmask<=30?Mn(this.netLong+this.size-2):Mn(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Mn(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):(Na(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Mn(this.netLong+this.size*e),this.mask)}forEach(e){let t=Na(this.first),n=Na(this.last),o=0;for(;t<=n;)e(Mn(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};Oa.Netmask4Impl=n4});var g9=sn(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.Netmask6Impl=void 0;Ba.ip6bigint=i4;Ba.bigint2ip6=xi;var AN=o4(),s4=(1n<<128n)-1n;function i4(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,AN.ip2long)(n),s=r.substring(0,t+1)+"0:0";return m9(s)&~0xffffffffn|BigInt(o)}return m9(r)}function m9(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.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 o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function xi(r){if(r<0n||r>s4)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,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),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 a4=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=s4>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=i4(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=xi(this.netBigint),this.mask=xi(this.maskBigint),this.hostmask=xi(~this.maskBigint&s4),this.first=this.base,this.last=xi(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):(i4(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(xi(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(xi(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Ba.Netmask6Impl=a4});var y9=sn(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.long2ip=ss.ip2long=ss.Netmask=void 0;var Uh=o4();Object.defineProperty(ss,"ip2long",{enumerable:!0,get:function(){return Uh.ip2long}});Object.defineProperty(ss,"long2ip",{enumerable:!0,get:function(){return Uh.long2ip}});var IN=g9(),c4=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 IN.Netmask6Impl(e,t):this._impl=new Uh.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 Uh.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()}};ss.Netmask=c4});var dA=sn((Ppe,Ny)=>{"use strict";var AF=Object.prototype.hasOwnProperty,fr="~";function Td(){}Object.create&&(Td.prototype=Object.create(null),new Td().__proto__||(fr=!1));function IF(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function uA(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new IF(t,n||r,o),i=fr?fr+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function xm(r,e){--r._eventsCount===0?r._events=new Td:delete r._events[e]}function Zt(){this._events=new Td,this._eventsCount=0}Zt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)AF.call(t,n)&&e.push(fr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Zt.prototype.listeners=function(e){var t=fr?fr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Zt.prototype.listenerCount=function(e){var t=fr?fr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Zt.prototype.emit=function(e,t,n,o,s,i){var a=fr?fr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,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,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};Zt.prototype.on=function(e,t,n){return uA(this,e,t,n,!1)};Zt.prototype.once=function(e,t,n){return uA(this,e,t,n,!0)};Zt.prototype.removeListener=function(e,t,n,o){var s=fr?fr+e:e;if(!this._events[s])return this;if(!t)return xm(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&xm(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:xm(this,s)}return this};Zt.prototype.removeAllListeners=function(e){var t;return e?(t=fr?fr+e:e,this._events[t]&&xm(this,t)):(this._events=new Td,this._eventsCount=0),this};Zt.prototype.off=Zt.prototype.removeListener;Zt.prototype.addListener=Zt.prototype.on;Zt.prefixed=fr;Zt.EventEmitter=Zt;typeof Ny<"u"&&(Ny.exports=Zt)});var pA=sn((Jpe,hA)=>{hA.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var DA=sn((mge,LA)=>{"use strict";function QF(r){return r>=55296&&r<=56319}function JF(r){return r>=56320&&r<=57343}LA.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,s=0,i,a,c=0;c<o;c+=1){if(i=t.charCodeAt(c),a=t[c],QF(i)&&JF(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),s+=e(a),s===n)return t.slice(0,c+1);if(s>n)return t.slice(0,c-a.length+1)}return t}});var NA=sn((gge,RA)=>{"use strict";function ZF(r){return r>=55296&&r<=56319}function e$(r){return r>=56320&&r<=57343}RA.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,s=null,i=0;i<t;i++)o=e.charCodeAt(i),e$(o)?s!=null&&ZF(s)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),s=o;return n}});var BA=sn((yge,OA)=>{"use strict";var t$=DA(),r$=NA();OA.exports=t$.bind(null,r$)});var i8=sn((wge,UA)=>{"use strict";var n$=BA(),o$=/[\/\?<>\\:\*\|"]/g,s$=/[\x00-\x1f\x80-\x9f]/g,i$=/^\.+$/,a$=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function c$(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 MA(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(o$,e).replace(s$,e).replace(i$,e).replace(a$,e);return t=c$(t,e),n$(t,255)}UA.exports=function(r,e){var t=e&&e.replacement||"",n=MA(r,t);return t===""?n:MA(n,"")}});var FA=sn(Oc=>{"use strict";var u$="[object ArrayBuffer]",Bo=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===u$}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])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 o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},c8="string",d$=/^[0-9a-f\s]+$/i,f$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,h$=/^[a-zA-Z0-9-_]+$/,Hm=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Bo.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},rn=class{static toString(e,t=!1){let n=Bo.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},qm=class r{static isHex(e){return typeof e===c8&&d$.test(e)}static isBase64(e){return typeof e===c8&&f$.test(e)}static isBase64Url(e){return typeof e===c8&&h$.test(e)}static ToString(e,t="utf8"){let n=Bo.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 rn.toString(n,!0);case"utf16":case"utf16be":return rn.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 rn.fromString(e,!0);case"utf16":case"utf16be":return rn.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Bo.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 Hm.fromString(e);case"utf16":case"utf16be":return rn.fromString(e);case"utf16le":case"usc2":return rn.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 Hm.toString(e);case"utf16":case"utf16be":return rn.toString(e);case"utf16le":case"usc2":return rn.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Bo.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Bo.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];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 o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return rn.toString(e,t)}static FromUtf16String(e,t=!1){return rn.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,"")||""}};qm.DEFAULT_UTF8_ENCODING="utf8";function p$(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function m$(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function g$(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Oc.BufferSourceConverter=Bo;Oc.Convert=qm;Oc.assign=p$;Oc.combine=m$;Oc.isEqual=g$});var R_=sn(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.parseCookie=L_;lo.parse=L_;lo.stringifyCookie=WG;lo.stringifySetCookie=R2;lo.serialize=R2;lo.parseSetCookie=GG;lo.stringifySetCookie=R2;lo.serialize=R2;var __=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,P_=/^[\u0021-\u003A\u003C-\u007E]*$/,KG=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,VG=/^[\u0020-\u003A\u003D-\u007E]*$/,HG=/^-?\d+$/,qG=Object.prototype.toString,zG=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function L_(r,e){let t=new zG,n=r.length;if(n<2)return t;let o=e?.decode||D_,s=0;do{let i=bw(r,s,n);if(i===-1)break;let a=ww(r,s,n);if(i>a){s=r.lastIndexOf(";",i-1)+1;continue}let c=Hs(r,s,i);t[c]===void 0&&(t[c]=o(Hs(r,i+1,a))),s=a+1}while(s<n);return t}function WG(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let o of Object.keys(r)){let s=r[o];if(s===void 0)continue;if(!__.test(o))throw new TypeError(`cookie name is invalid: ${o}`);let i=t(s);if(!P_.test(i))throw new TypeError(`cookie val is invalid: ${s}`);n.push(`${o}=${i}`)}return n.join("; ")}function R2(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},s=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!__.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let i=n.value?s(n.value):"";if(!P_.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(!KG.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!VG.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!jG(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 GG(r,e){let t=e?.decode||D_,n=r.length,o=ww(r,0,n),s=bw(r,0,o),i=s===-1?{name:"",value:t(Hs(r,0,o))}:{name:Hs(r,0,s),value:t(Hs(r,s+1,o))},a=o+1;for(;a<n;){let c=ww(r,a,n),l=bw(r,a,c),u=l===-1?Hs(r,a,c):Hs(r,a,l),d=l===-1?void 0:Hs(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&&HG.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 ww(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function bw(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Hs(r,e,t){let n=e,o=t;do{let s=r.charCodeAt(n);if(s!==32&&s!==9)break}while(++n<o);for(;o>n;){let s=r.charCodeAt(o-1);if(s!==32&&s!==9)break;o--}return r.slice(n,o)}function D_(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function jG(r){return qG.call(r)==="[object Date]"}});var ZY={};V(ZY,{DEFAULT_CID_PEER_FILTER_SIZE:()=>j3,DEFAULT_SESSION_MAX_PROVIDERS:()=>G3,DEFAULT_SESSION_MIN_PROVIDERS:()=>W3,InsufficientProvidersError:()=>au,InvalidCodecError:()=>Y3,NoRoutersAvailableError:()=>os,UnknownCodecError:()=>lu,UnknownCryptoError:()=>uu,UnknownHashAlgorithmError:()=>cu,createHelia:()=>JY,createHeliaLight:()=>rD,isPrivateKey:()=>r9,isPublicKey:()=>z3});var gb=Symbol.for("@libp2p/connection");var ri=Symbol.for("@libp2p/content-routing");var nr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},lh=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},uh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},A=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},fo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},$l=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Kl=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var ni=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},ba=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},an=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},xa=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Nn=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Vl=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Te=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ea=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},On=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},dh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},va=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},fh=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},pe=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},oi=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Bn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Cr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Zo=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},si=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Hl=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},hh=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Sa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},cn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ph=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},es=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},mh=class extends es{constructor(e,t){super(!0,e,t)}},gh=class extends es{constructor(e,t){super(!1,e,t)}};var ii=Symbol.for("@libp2p/peer-discovery");var yh=Symbol.for("@libp2p/peer-id");function yr(r){return!!r?.[yh]}var ai=Symbol.for("@libp2p/peer-routing");var ci="keep-alive";function wh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ht(...r){let e=[];for(let t of r)wh(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 Ct(...r){let e=[];for(let t of r)wh(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 ts=Symbol.for("@libp2p/transport");var ql;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(ql||(ql={}));function lD(r){return typeof r?.handleEvent=="function"}function uD(r){return(r!==!0&&r!==!1&&r?.once)??!1}var le=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=uD(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}lD(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var xe=Symbol.for("@libp2p/service-capabilities"),kr=Symbol.for("@libp2p/service-dependencies");var R=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function de(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var FX=new Uint8Array(0);function wb(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 wr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return li(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return li(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function bb(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var yb=4096;function xb(r){let e=r.length;if(e<=yb)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=yb));return t}function dD(r){return r?.buffer instanceof ArrayBuffer}function li(r){return dD(r)?r:r.slice()}var n3={};V(n3,{base32:()=>pt,base32hex:()=>ED,base32hexpad:()=>SD,base32hexpadupper:()=>AD,base32hexupper:()=>vD,base32pad:()=>bD,base32padupper:()=>xD,base32upper:()=>wD,base32z:()=>ID});function fD(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}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 w=0,x=0,E=0,S=m.length;E!==S&&m[E]===0;)E++,w++;for(var T=(S-E)*h+1>>>0,I=new Uint8Array(T);E!==S;){for(var C=m[E],U=0,j=T-1;(C!==0||U<x)&&j!==-1;j--,U++)C+=256*I[j]>>>0,I[j]=C%u>>>0,C=C/u>>>0;if(C!==0)throw new Error("Non-zero carry");x=U,E++}for(var z=T-x;z!==T&&I[z]===0;)z++;for(var v=d.repeat(w);z<T;++z)v+=r.charAt(I[z]);return v}function y(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var w=0;if(m[w]!==" "){for(var x=0,E=0;m[w]===d;)x++,w++;for(var S=(m.length-w)*f+1>>>0,T=new Uint8Array(S);m[w];){var I=n[m.charCodeAt(w)];if(I===255)return;for(var C=0,U=S-1;(I!==0||C<E)&&U!==-1;U--,C++)I+=u*T[U]>>>0,T[U]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");E=C,w++}if(m[w]!==" "){for(var j=S-E;j!==S&&T[j]===0;)j++;for(var z=new Uint8Array(x+(S-j)),v=x;j!==S;)z[v++]=T[j++];return z}}}function g(m){var w=y(m);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:y,decode:g}}var hD=fD,pD=hD,Eb=pD;var Zg=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")}},e3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return vb(this,e)}},t3=class{decoders;constructor(e){this.decoders=e}or(e){return vb(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 vb(r,e){return new t3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var r3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Zg(e,t,n),this.decoder=new e3(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Aa({name:r,prefix:e,encode:t,decode:n}){return new r3(r,e,t,n)}function rs({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Eb(t,r,n);return Aa({prefix:e,name:r,encode:o,decode:i=>wr(s(i))})}function mD(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function gD(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function yD(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function ot({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=yD(n,o);return Aa({prefix:e,name:r,encode(i){return gD(i,n,t)},decode(i){return mD(i,s,t,r)}})}var pt=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),wD=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),bD=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),xD=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),ED=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),vD=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),SD=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),AD=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),ID=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var o3={};V(o3,{base36:()=>or,base36upper:()=>TD});var or=rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),TD=rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var s3={};V(s3,{base58btc:()=>ge,base58flickr:()=>CD});var ge=rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),CD=rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ze={};V(ze,{Digest:()=>ui,create:()=>sr,decode:()=>Ee,equals:()=>a3,hasCode:()=>WD});var kD=Ib,Sb=128,_D=127,PD=~_D,LD=Math.pow(2,31);function Ib(r,e,t){e=e||[],t=t||0;for(var n=t;r>=LD;)e[t++]=r&255|Sb,r/=128;for(;r&PD;)e[t++]=r&255|Sb,r>>>=7;return e[t]=r|0,Ib.bytes=t-n+1,e}var DD=i3,RD=128,Ab=127;function i3(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw i3.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ab)<<o:(i&Ab)*Math.pow(2,o),o+=7}while(i>=RD);return i3.bytes=s-n,t}var ND=Math.pow(2,7),OD=Math.pow(2,14),BD=Math.pow(2,21),MD=Math.pow(2,28),UD=Math.pow(2,35),FD=Math.pow(2,42),$D=Math.pow(2,49),KD=Math.pow(2,56),VD=Math.pow(2,63),HD=function(r){return r<ND?1:r<OD?2:r<BD?3:r<MD?4:r<UD?5:r<FD?6:r<$D?7:r<KD?8:r<VD?9:10},qD={encode:kD,decode:DD,encodingLength:HD},zD=qD,zl=zD;function Wl(r,e=0){return[zl.decode(r,e),zl.decode.bytes]}function Ia(r,e,t=0){return zl.encode(r,e,t),e}function Ta(r){return zl.encodingLength(r)}function sr(r,e){let t=e.byteLength,n=Ta(r),o=n+Ta(t),s=new Uint8Array(o+t);return Ia(r,s,0),Ia(t,s,n),s.set(e,o),new ui(r,t,e,s)}function Ee(r){let e=wr(r),[t,n]=Wl(e),[o,s]=Wl(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ui(t,o,i,e)}function a3(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&wb(r.bytes,t.bytes)}}var ui=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=li(n),this.bytes=li(o)}};function WD(r,e){return r.code===e}function Tb(r,e){let{bytes:t,version:n}=r;return n===0?jD(t,c3(r),e??ge.encoder):YD(t,c3(r),e??pt.encoder)}var Cb=new WeakMap;function c3(r){let e=Cb.get(r);if(e==null){let t=new Map;return Cb.set(r,t),t}return e}var K=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=li(o),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!==Gl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==XD)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=sr(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&&a3(e.multihash,n.multihash)}toString(e){return Tb(this,e)}toJSON(){return{"/":Tb(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??kb(n,o,s.bytes))}else if(t[QD]===!0){let{version:n,multihash:o,code:s}=t,i=Ee(o);return r.create(n,s,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!==Gl)throw new Error(`Version 0 CID must use dag-pb (code: ${Gl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=kb(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Gl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=wr(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new ui(t.multihashCode,t.digestSize,s,o);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]=Wl(e.subarray(t));return t+=f,d},o=n(),s=Gl;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=GD(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return c3(s).set(n,e),s}};function GD(r,e){switch(r[0]){case"Q":{let t=e??ge;return[ge.prefix,t.decode(`${ge.prefix}${r}`)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case pt.prefix:{let t=e??pt;return[pt.prefix,t.decode(r)]}case or.prefix:{let t=e??or;return[or.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 jD(r,e,t){let{prefix:n}=t;if(n!==ge.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function YD(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Gl=112,XD=18;function kb(r,e,t){let n=Ta(r),o=n+Ta(e),s=new Uint8Array(o+t.byteLength);return Ia(r,s,0),Ia(e,s,n),s.set(t,o),s}var QD=Symbol.for("@ipld/js-cid/CID");var JD=20;function jl({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new l3(r,e,t,n,o)}var l3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??JD,this.maxDigestLength=s}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?_b(n,this.code,t?.truncate):n.then(o=>_b(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _b(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 sr(e,r)}var u3={};V(u3,{base64:()=>$e,base64pad:()=>Yl,base64url:()=>ne,base64urlpad:()=>ZD});var $e=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yl=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ne=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ZD=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var d3={};V(d3,{identity:()=>Ze});var Lb=0,eR="identity",Db=wr;function tR(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 sr(Lb,Db(r))}var Ze={code:Lb,name:eR,encode:Db,digest:tR};function me(r=0){return new Uint8Array(r)}function st(r=0){return new Uint8Array(r)}function rR(r){return r?.buffer instanceof ArrayBuffer}function xh(r){if(rR(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ke(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=st(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return xh(t)}function te(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 Nb=Symbol.for("@achingbrain/uint8arraylist");function Rb(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ca(r){return!!r?.[Nb]}var Y=class r{bufs;length;[Nb]=!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(Ca(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ca(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=Rb(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Rb(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(Ca(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ke(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ke(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(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(!Ca(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;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=st(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=me(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=me(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=me(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=st(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=me(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=me(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=me(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=me(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=me(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function nR(r){return r.buffer instanceof ArrayBuffer}function ee(r){return nR(r)?r:r.slice()}var oR=parseInt("11111",2),f3=parseInt("10000000",2),sR=parseInt("01111111",2),Ob={0:Xl,1:Xl,2:iR,3:lR,4:uR,5:cR,6:aR,16:Xl,22:Xl,48:Xl};function ln(r,e={offset:0}){let t=r[e.offset]&oR;if(e.offset++,Ob[t]!=null)return Ob[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Ql(r,e){let t=0;if((r[e.offset]&f3)===f3){let n=r[e.offset]&sR,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Xl(r,e){Ql(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ln(r,e);if(n===null)break;t.push(n)}return t}function iR(r,e){let t=Ql(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function aR(r,e){let t=Ql(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${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 cR(r,e){return e.offset++,null}function lR(r,e){let t=Ql(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function uR(r,e){let t=Ql(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function dR(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Eh(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=dR(r.byteLength);return new Y(Uint8Array.from([e.byteLength|f3]),e)}function ir(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),Eh(e),e)}function Jl(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),Eh(t),t)}function Bb(r){return new Y(Uint8Array.from([4]),Eh(r),r)}function un(r,e=48){let t=new Y;for(let n of r)t.append(ee(n.subarray()));return new Y(Uint8Array.from([e]),Eh(t),t)}var Ve=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var fR=Math.pow(2,7),hR=Math.pow(2,14),pR=Math.pow(2,21),h3=Math.pow(2,28),p3=Math.pow(2,35),m3=Math.pow(2,42),g3=Math.pow(2,49),Le=128,Wt=127;function we(r){if(r<fR)return 1;if(r<hR)return 2;if(r<pR)return 3;if(r<h3)return 4;if(r<p3)return 5;if(r<m3)return 6;if(r<g3)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ka(r,e,t=0){switch(we(r)){case 8:e[t++]=r&255|Le,r/=128;case 7:e[t++]=r&255|Le,r/=128;case 6:e[t++]=r&255|Le,r/=128;case 5:e[t++]=r&255|Le,r/=128;case 4:e[t++]=r&255|Le,r>>>=7;case 3:e[t++]=r&255|Le,r>>>=7;case 2:e[t++]=r&255|Le,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function mR(r,e,t=0){switch(we(r)){case 8:e.set(t++,r&255|Le),r/=128;case 7:e.set(t++,r&255|Le),r/=128;case 6:e.set(t++,r&255|Le),r/=128;case 5:e.set(t++,r&255|Le),r/=128;case 4:e.set(t++,r&255|Le),r>>>=7;case 3:e.set(t++,r&255|Le),r>>>=7;case 2:e.set(t++,r&255|Le),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function y3(r,e){let t=r[e],n=0;if(n+=t&Wt,t<Le||(t=r[e+1],n+=(t&Wt)<<7,t<Le)||(t=r[e+2],n+=(t&Wt)<<14,t<Le)||(t=r[e+3],n+=(t&Wt)<<21,t<Le)||(t=r[e+4],n+=(t&Wt)*h3,t<Le)||(t=r[e+5],n+=(t&Wt)*p3,t<Le)||(t=r[e+6],n+=(t&Wt)*m3,t<Le)||(t=r[e+7],n+=(t&Wt)*g3,t<Le))return n;throw new RangeError("Could not decode varint")}function gR(r,e){let t=r.get(e),n=0;if(n+=t&Wt,t<Le||(t=r.get(e+1),n+=(t&Wt)<<7,t<Le)||(t=r.get(e+2),n+=(t&Wt)<<14,t<Le)||(t=r.get(e+3),n+=(t&Wt)<<21,t<Le)||(t=r.get(e+4),n+=(t&Wt)*h3,t<Le)||(t=r.get(e+5),n+=(t&Wt)*p3,t<Le)||(t=r.get(e+6),n+=(t&Wt)*m3,t<Le)||(t=r.get(e+7),n+=(t&Wt)*g3,t<Le))return n;throw new RangeError("Could not decode varint")}function Gt(r,e,t=0){return e==null&&(e=st(we(r))),e instanceof Uint8Array?ka(r,e,t):mR(r,e,t)}function _r(r,e=0){return r instanceof Uint8Array?y3(r,e):gR(r,e)}var w3=new Float32Array([-0]),ns=new Uint8Array(w3.buffer);function Mb(r,e,t){w3[0]=r,e[t]=ns[0],e[t+1]=ns[1],e[t+2]=ns[2],e[t+3]=ns[3]}function Ub(r,e){return ns[0]=r[e],ns[1]=r[e+1],ns[2]=r[e+2],ns[3]=r[e+3],w3[0]}var b3=new Float64Array([-0]),jt=new Uint8Array(b3.buffer);function Fb(r,e,t){b3[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3],e[t+4]=jt[4],e[t+5]=jt[5],e[t+6]=jt[6],e[t+7]=jt[7]}function $b(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],jt[4]=r[e+4],jt[5]=r[e+5],jt[6]=r[e+6],jt[7]=r[e+7],b3[0]}var yR=BigInt(Number.MAX_SAFE_INTEGER),wR=BigInt(Number.MIN_SAFE_INTEGER),Pr=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 di;if(e<yR&&e>wR)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Kb&&(o=0n,++n>Kb&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return di;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):di}},di=new Pr(0,0);di.toBigInt=function(){return 0n};di.zzEncode=di.zzDecode=function(){return this};di.length=function(){return 1};var Kb=4294967296n;function Vb(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 Hb(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function x3(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function dn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function vh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var E3=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ee(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,dn(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 dn(this,4);return vh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw dn(this,4);return vh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw dn(this,4);let e=Ub(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw dn(this,4);let e=$b(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 dn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hb(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw dn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw dn(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 Pr(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 dn(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 dn(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 dn(this,8);let e=vh(this.buf,this.pos+=4),t=vh(this.buf,this.pos+=4);return new Pr(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=y3(this.buf,this.pos);return this.pos+=we(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 Zl(r){return new E3(r instanceof Uint8Array?r:r.subarray())}function oe(r,e,t){let n=Zl(r);return e.decode(n,void 0,t)}var v3={};V(v3,{base10:()=>bR});var bR=rs({prefix:"9",name:"base10",alphabet:"0123456789"});var S3={};V(S3,{base16:()=>xR,base16upper:()=>ER});var xR=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),ER=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var A3={};V(A3,{base2:()=>vR});var vR=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var I3={};V(I3,{base256emoji:()=>CR});var zb=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}"),SR=zb.reduce((r,e,t)=>(r[t]=e,r),[]),AR=zb.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function IR(r){return r.reduce((e,t)=>(e+=SR[t],e),"")}function TR(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=AR[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var CR=Aa({prefix:"\u{1F680}",name:"base256emoji",encode:IR,decode:TR});var T3={};V(T3,{base8:()=>kR});var kR=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var C3={};V(C3,{identity:()=>_R});var _R=Aa({prefix:"\0",name:"identity",encode:r=>xb(wr(r)),decode:r=>wr(bb(r))});var Sh={};V(Sh,{code:()=>RR,decode:()=>OR,encode:()=>NR,name:()=>DR});var PR=new TextEncoder,LR=new TextDecoder,DR="json",RR=512;function NR(r){return PR.encode(JSON.stringify(r))}function OR(r){return JSON.parse(LR.decode(r))}var fi={};V(fi,{code:()=>po,decode:()=>UR,encode:()=>MR,name:()=>BR});var BR="raw",po=85;function MR(r){return wr(r)}function UR(r){return wr(r)}var _3={};V(_3,{sha256:()=>He,sha512:()=>k3});function Wb(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var He=jl({name:"sha2-256",code:18,encode:Wb("SHA-256")}),k3=jl({name:"sha2-512",code:19,encode:Wb("SHA-512")});var hi={...C3,...A3,...T3,...v3,...S3,...n3,...o3,...s3,...u3,...I3},GQ={..._3,...d3};function jb(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Gb=jb("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),P3=jb("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=st(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),FR={utf8:Gb,"utf-8":Gb,hex:hi.base16,latin1:P3,ascii:P3,binary:P3,...hi},Ah=FR;function O(r,e="utf8"){let t=Ah[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,o=e;return function(i){if(i<1||i>t)return st(i);o+i>e&&(n=st(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var pi=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function D3(){}var N3=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},$R=L3();function KR(r){return globalThis.Buffer!=null?st(r):$R(r)}var tu=class{len;head;tail;states;constructor(){this.len=0,this.head=new pi(D3,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new pi(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new O3((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(Ih,10,Pr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Pr.fromBigInt(e);return this._push(Ih,t.length(),t)}uint64Number(e){return this._push(ka,we(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=Pr.fromBigInt(e).zzEncode();return this._push(Ih,t.length(),t)}sint64Number(e){let t=Pr.fromNumber(e).zzEncode();return this._push(Ih,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(R3,1,e?1:0)}fixed32(e){return this._push(eu,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pr.fromBigInt(e);return this._push(eu,4,t.lo)._push(eu,4,t.hi)}fixed64Number(e){let t=Pr.fromNumber(e);return this._push(eu,4,t.lo)._push(eu,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(Mb,4,e)}double(e){return this._push(Fb,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(R3,1,0):this.uint32(t)._push(HR,t,e)}string(e){let t=Vb(e);return t!==0?this.uint32(t)._push(x3,t,e):this._push(R3,1,0)}fork(){return this.states=new N3(this),this.head=this.tail=new pi(D3,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 pi(D3,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=KR(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function R3(r,e,t){e[t]=r&255}function VR(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var O3=class extends pi{next;constructor(e,t){super(VR,e,t),this.next=void 0}};function Ih(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 eu(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 HR(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(tu.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(qR,e,r),this},tu.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zR,e,r),this});function qR(r,e,t){e.set(r,t)}function zR(r,e,t){r.length<40?x3(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(O(r),t)}function B3(){return new tu}function se(r,e){let t=B3();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ie(r,e,t){let n=Zl(r);yield*e.stream(n,void 0,"$",t)}var Th={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ch(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function et(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ch("enum",Th.VARINT,t,n,o)}function ae(r,e,t){return Ch("message",Th.LENGTH_DELIMITED,r,e,t)}var he=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ru=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var kh;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(kh||(kh={}));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=()=>et(M3)})(kh||(kh={}));var br;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),i.int32(s.Type)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=s.int32();break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:s.int32()};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(br||(br={}));var ar;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),i.int32(s.Type)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=s.int32();break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:s.int32()};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(ar||(ar={}));var WR=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),GR=Uint8Array.from([6,5,43,129,4,0,34]),jR=Uint8Array.from([6,5,43,129,4,0,35]),Yb={ext:!0,kty:"EC",crv:"P-256"},Xb={ext:!0,kty:"EC",crv:"P-384"},Qb={ext:!0,kty:"EC",crv:"P-521"},_a=32,Pa=48,La=66,nu=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return Ze.digest(this.toProtobuf())}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return br.encode({Type:this.code,Data:JR(this.jwk)})}async verify(e,t,n){let o=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,ee(t),ee(e));return n?.signal?.throwIfAborted(),s}},_h=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return ar.encode({Type:this.code,Data:ZR(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"]),o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,ee(e));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}},U3=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"]),o=await crypto.subtle.exportKey("jwk",n.privateKey),s=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new _h(o,new nu(s))}async publicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let o=QR(n.Data);return new nu(o)}async privateKeyFromProtobuf(e,t){let n=ar.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=XR(n.Data),s=YR(o);return t?.signal?.throwIfAborted(),new _h(o,new nu(s))}};function F3(){return new U3}function YR(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function XR(r){let e=ln(r),t=e[1],n=ne.baseEncode(t),o=e[2][1][0],s=1,i,a;if(t.byteLength===_a)return i=ne.baseEncode(o.subarray(s,s+_a)),a=ne.baseEncode(o.subarray(s+_a)),{...Yb,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===Pa)return i=ne.baseEncode(o.subarray(s,s+Pa)),a=ne.baseEncode(o.subarray(s+Pa)),{...Xb,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===La)return i=ne.baseEncode(o.subarray(s,s+La)),a=ne.baseEncode(o.subarray(s+La)),{...Qb,key_ops:["sign"],d:n,x:i,y:a};throw new Ve(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function QR(r){let t=ln(r)[1][1][0],n=1,o,s;if(t.byteLength===_a*2+1)return o=ne.baseEncode(t.subarray(n,n+_a)),s=ne.baseEncode(t.subarray(n+_a)),{...Yb,key_ops:["verify"],x:o,y:s};if(t.byteLength===Pa*2+1)return o=ne.baseEncode(t.subarray(n,n+Pa)),s=ne.baseEncode(t.subarray(n+Pa)),{...Xb,key_ops:["verify"],x:o,y:s};if(t.byteLength===La*2+1)return o=ne.baseEncode(t.subarray(n,n+La)),s=ne.baseEncode(t.subarray(n+La)),{...Qb,key_ops:["verify"],x:o,y:s};throw new Ve(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function JR(r){return un([ir(Uint8Array.from([1])),un([Jb(r.crv)],160),un([Jl(new Y(Uint8Array.from([4]),ne.baseDecode(r.x??""),ne.baseDecode(r.y??"")))],161)]).subarray()}function ZR(r){return un([ir(Uint8Array.from([1])),Bb(ne.baseDecode(r.d??"")),un([Jb(r.crv)],160),un([Jl(new Y(Uint8Array.from([4]),ne.baseDecode(r.x??""),ne.baseDecode(r.y??"")))],161)]).subarray()}function Jb(r){if(r==="P-256")return WR;if(r==="P-384")return GR;if(r==="P-521")return jR;throw new Ve(`Invalid curve ${r}`)}var eN=32,ou=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return Ze.digest(this.toProtobuf())}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return br.encode({Type:this.code,Data:ne.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let o=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),s=await crypto.subtle.verify({name:"Ed25519"},o,ee(t),ee(e));return n?.signal?.throwIfAborted(),s}},Ph=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return ar.encode({Type:this.code,Data:Ke([ne.baseDecode(this.jwk.d??""),ne.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"]),o=await crypto.subtle.sign({name:"Ed25519"},n,ee(e));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}},$3=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),o=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Ph(n,new ou(o))}async publicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let o=oN(n.Data);return new ou(o)}async privateKeyFromProtobuf(e,t){let n=ar.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=await tN(n.Data,t),s=nN(o);return new Ph(o,new ou(s))}};function K3(){return new $3}async function tN(r,e){let t=r.subarray(0,eN),n=rN(t),o=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),s=await crypto.subtle.exportKey("jwk",o);return e?.signal?.throwIfAborted(),s}var Zb=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function rN(r){return Ke([Zb,Uint8Array.from([r.byteLength]),r],Zb.byteLength+1+r.byteLength)}function nN(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function oN(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:ne.baseEncode(r)}}var q3=8192,su=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(t9(e)>q3)throw new Ve("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return K.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(or)}toProtobuf(){return uN(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let o=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),s=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,ee(t),ee(e));return n?.signal?.throwIfAborted(),s}},Lh=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(t9(e)>q3)throw new Ve("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return dN(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"]),o=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,ee(e));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}},H3=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>q3)throw new Ve("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"]),o=await crypto.subtle.exportKey("jwk",n.privateKey),s=await crypto.subtle.exportKey("jwk",n.publicKey),i=await V3(o);return e?.signal?.throwIfAborted(),new Lh(o,new su(s,i))}async publicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=cN(n.Data),s=await V3(o);return t?.signal?.throwIfAborted(),new su(o,s)}async privateKeyFromProtobuf(e,t){let n=ar.decode(e);if(n.Data==null)throw new Ve("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ve("Incorrect Type field in protobuf");let o=ln(n.Data),s=sN(o),i=lN(s),a=await V3(i);return t?.signal?.throwIfAborted(),new Lh(s,new su(i,a))}};function iu(){return new H3}function sN(r){return{alg:"RS256",kty:"RSA",n:ne.baseEncode(r[1]),e:ne.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:ne.baseEncode(r[3]),p:ne.baseEncode(r[4]),q:ne.baseEncode(r[5]),dp:ne.baseEncode(r[6]),dq:ne.baseEncode(r[7]),qi:ne.baseEncode(r[8])}}function iN(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 Ve("JWK was missing components");return un([ir(Uint8Array.from([0])),ir(ne.baseDecode(r.n)),ir(ne.baseDecode(r.e)),ir(ne.baseDecode(r.d)),ir(ne.baseDecode(r.p)),ir(ne.baseDecode(r.q)),ir(ne.baseDecode(r.dp)),ir(ne.baseDecode(r.dq)),ir(ne.baseDecode(r.qi))]).subarray()}var aN=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function e9(r){if(r.n==null||r.e==null)throw new Ve("JWK public key was missing components");return un([aN,Jl(un([ir(ne.baseDecode(r.n)),ir(ne.baseDecode(r.e))]))]).subarray()}function cN(r){let e=ln(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=ln(e[1]);return{kty:"RSA",n:ne.baseEncode(t[0]),e:ne.baseEncode(t[1])}}function lN(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function t9(r){if(r.kty!=="RSA")throw new Ve("Invalid key type");if(r.n==null)throw new Ve("Invalid key modulus");return ne.baseDecode(r.n).length*8}async function V3(r){let e=br.encode({Type:0,Data:e9(r)});return He.digest(e)}function uN(r,e){return br.encode({Type:r,Data:e9(e)})}function dN(r,e){return ar.encode({Type:r,Data:iN(e)})}function z3(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.verify=="function"}function r9(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.sign=="function"&&z3(r.publicKey)}var W3=1,G3=5,j3=100;var au=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},os=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},cu=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},lu=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},Y3=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}},uu=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"};var X3={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},n9={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},o9=new globalThis.TextEncoder;function fN(r,e){let t=X3[e],n=n9[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function hN(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=X3[e],o=n9[e],s=r;for(;s.length>0;){let i=o9.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Q3(r,{size:e=32,utf8Buffer:t}={}){if(!X3[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 hN(r,e,t);r=o9.encode(r)}return fN(r,e)}var du={hash:r=>Number(Q3(r,{size:32})),hashV:(r,e)=>pN(du.hash(r,e))};function pN(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),O(e,"base16")}var J3=64,fn=class{fp;h;seed;constructor(e,t,n,o=2){if(o>J3)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=me(o);for(let a=0;a<i.length;a++)i[a]=s[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?te(this.fp,e.fp):!1}};function mi(r,e){return Math.floor(Math.random()*(e-r))+r}var gi=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof fn))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof fn))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 fn))throw new TypeError("Invalid Fingerprint");let t=mi(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof fn))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var mN=500,fu=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??du,this.seed=e.seed??mi(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=O(e));let t=new fn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new gi(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new gi(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[mi(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new gi(this.bucketSize));for(let a=0;a<mN;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 gi(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=O(e));let t=new fn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=O(e));let t=new fn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},gN={1:.5,2:.84,4:.95,8:.98};function yN(r=.001){return r>.002?2:r>1e-5?4:8}function s9(r,e=.001){let t=yN(e),n=gN[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),J3);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Dh=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??du,this.seed=e.seed??mi(0,Math.pow(2,10)),this.filterSeries=[new fu({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=O(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new fu({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=O(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=O(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 Nt(r,e=.001,t){return new Dh({...s9(r,e),...t??{}})}function Z3(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 ce(r){let e=Z3(r);if(e==null)throw new A(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Rh=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var i9=45,wN=15,Da=new Rh;function Nh(r){if(!(r.length>wN))return Da.new(r).parseWith(()=>Da.readIPv4Addr())}function Oh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>i9))return Da.new(r).parseWith(()=>Da.readIPv6Addr())}function Ra(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>i9)return;let t=Da.new(r).parseWith(()=>Da.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 a9(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function c9(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function e4(r){switch(r.length){case yi:return r.join(".");case wi:{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 l9(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function u9(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var yi=4,wi=16,jZ=parseInt("0xFFFF",16),bN=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hu(r,e){e.length===wi&&r.length===yi&&a9(e,0,11)&&(e=e.slice(12)),e.length===yi&&r.length===wi&&c9(r,bN,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function d9(r,e){if(typeof e=="string"&&(e=Ra(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 t4(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=yi,o=Nh(e);if(o==null&&(n=wi,o=Oh(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=r4(s,8*n);return{network:hu(o,i),mask:i}}function r4(r,e){if(e!==8*yi&&e!==8*wi)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var bi=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=t4(e));else{let n=Ra(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Ra(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=r4(o,8*n.length);this.network=hu(n,this.mask)}}contains(e){return d9({network:this.network,mask:this.mask},e)}toString(){let e=l9(this.mask),t=e!==-1?String(e):u9(this.mask);return e4(this.network)+"/"+t}};function f9(r,e){return new bi(r).contains(e)}function Bh(r){try{let e=ce(r);return e.type==="ip6"?f9("2000::/3",e.host):!1}catch{return!1}}function h9(r){try{let e=ce(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 p9(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function pu(r){try{let e=ce(r);switch(e.type){case"ip4":case"ip6":return p9(e.host);default:return!1}}catch{return!1}}function Ot(r){return Z3(r)!==null}function hn(r){return!!Nh(r)}function Mh(r){return!!Oh(r)}var w9=ti(y9(),1),TN=["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"],CN=TN.map(r=>new w9.Netmask(r));function l4(r){for(let e of CN)if(e.contains(r))return!0;return!1}function kN(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function _N(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return l4(o)}function PN(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function LN(r){let e=r.split(":"),t=e[e.length-1];return l4(t)}function DN(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 Ma(r){if(hn(r))return l4(r);if(kN(r))return _N(r);if(PN(r))return LN(r);if(Mh(r))return DN(r)}function it(r){try{let e=ce(r);switch(e.type){case"ip4":case"ip6":return Ma(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function is(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 pn(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=st(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return xh(t)}function M(r,e="utf8"){let t=Ah[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Bt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},mo=class extends Error{static name="ValidationError";name="ValidationError"},Fh=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},$h=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function d4(r){return e=>M(e,r)}function f4(r){return e=>O(e,r)}function Ua(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ei(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function b9(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=O(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ei(n);return Ke([t,o],t.length+o.length)}function x9(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=pt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ei(n);return Ke([t,o],t.length+o.length)}function h4(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=M(e,"base32"),o=Ua(t);return`${n}:${o}`}var p4=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Bt("Invalid byte value in IP address");e[n]=o}),e},E9=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=hn(t[n]),i;s&&(i=p4(t[n]),t[n]=M(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,M(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Bt("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},v9=function(r){if(r.byteLength!==4)throw new Bt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},S9=function(r){if(r.byteLength!==16)throw new Bt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.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 Bt(`Invalid IPv6 address "${t}"`)}};function A9(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Bt(`Invalid IPv6 address "${r}"`)}}var u4=Object.values(hi).map(r=>r.decoder),RN=(function(){let r=u4[0].or(u4[1]);return u4.slice(2).forEach(e=>r=r.or(e)),r})();function I9(r){return RN.decode(r)}function T9(r){return e=>r.encoder.encode(e)}function NN(r){if(parseInt(r).toString()!==r)throw new mo("Value must be an integer")}function ON(r){if(r<0)throw new mo("Value must be a positive integer, or zero")}function BN(r){return e=>{if(e>r)throw new mo(`Value must be smaller than or equal to ${r}`)}}function MN(...r){return e=>{for(let t of r)t(e)}}var mu=MN(NN,ON,BN(65535));var kt=-1,m4=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 $h(`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)}))}},yo=new m4,QN=[{code:4,name:"ip4",size:32,valueToBytes:p4,bytesToValue:v9,validate:r=>{if(!hn(r))throw new mo(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:273,name:"udp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:33,name:"dccp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:41,name:"ip6",size:128,valueToBytes:E9,bytesToValue:S9,stringToValue:A9,validate:r=>{if(!Mh(r))throw new mo(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:kt},{code:43,name:"ipcidr",size:8,bytesToValue:d4("base10"),valueToBytes:f4("base10")},{code:53,name:"dns",size:kt},{code:54,name:"dns4",size:kt},{code:55,name:"dns6",size:kt},{code:56,name:"dnsaddr",size:kt},{code:132,name:"sctp",size:16,valueToBytes:Ei,bytesToValue:Ua,validate:mu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:kt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:kt,bytesToValue:d4("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?f4("base58btc")(r):K.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:h4,valueToBytes:b9},{code:445,name:"onion3",size:296,bytesToValue:h4,valueToBytes:x9},{code:446,name:"garlic64",size:kt},{code:447,name:"garlic32",size:kt},{code:448,name:"tls"},{code:449,name:"sni",size:kt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:kt,bytesToValue:T9(ne),valueToBytes:I9},{code:480,name:"http"},{code:481,name:"http-path",size:kt,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:kt}];QN.forEach(r=>{yo.addProtocol(r)});function C9(r){let e=[],t=0;for(;t<r.length;){let n=_r(r,t),o=yo.getProtocol(n),s=we(n),i=JN(o,r,t+s),a=0;i>0&&o.size===kt&&(a=we(i));let c=s+a+i,l={code:n,name:o.name,bytes:ee(r.subarray(t,t+c))};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??M(d)}e.push(l),t+=c}return e}function k9(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=yo.getProtocol(n.code),s=we(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??O(n.value),a=i.byteLength,o.size===kt&&(c=we(a)));let l=new Uint8Array(s+c+a),u=0;ka(n.code,l,u),u+=s,i!=null&&(o.size===kt&&(ka(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 _9(r){if(r.charAt(0)!=="/")throw new Bt('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=yo.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Bt(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Bt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Bt("Incomplete multiaddr");return e}function P9(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=yo.getProtocol(e.code);if(t==null)throw new Bt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function JN(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:_r(e,t)}var ZN=Symbol.for("nodejs.util.inspect.custom"),A4=Symbol.for("@multiformats/multiaddr");function eO(r){if(r==null&&(r="/"),jr(r))return r.getComponents();if(r instanceof Uint8Array)return C9(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),_9(r);if(Array.isArray(r))return r;throw new Bt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var zh=class r{[A4]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=eO(e),t.validate!==!1&&tO(this)}get bytes(){return this.#r==null&&(this.#r=k9(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=P9(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Fh(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return te(this.bytes,e.bytes)}[ZN](){return`Multiaddr(${this.toString()})`}};function tO(r){r.getComponents().forEach(e=>{let t=yo.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function jr(r){return!!r?.[A4]}function G(r){return new zh(r)}var De=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),re=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),L9=r=>({match:e=>r.match(e)===!1?e:!1}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Yt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),Se=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Re(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var rO=re(421),D9=Re(rO),Gh=re(54),jh=re(55),Yh=re(56),T4=re(53),Mte=Re(Gh,be(re(421))),Ute=Re(jh,be(re(421))),Fte=Re(Yh,be(re(421))),Xh=Re(Yt(T4,Yh,Gh,jh),be(re(421))),R9=Se(re(4),be(re(43))),N9=Se(be(re(42)),re(41),be(re(43))),C4=Yt(R9,N9),Va=Yt(C4,T4,Gh,jh,Yh),O9=Re(Yt(C4,Se(Yt(T4,Yh,Gh,jh),be(re(421))))),k4=Re(R9),_4=Re(N9),B9=Re(C4),P4=Se(Va,re(6)),Eu=Se(Va,re(273)),Si=Re(Se(P4,be(re(421)))),$te=Re(Eu),L4=Se(Eu,De(460),be(re(421))),Qh=Se(Eu,De(461),be(re(421))),nO=Yt(L4,Qh),Kte=Re(L4),M9=Re(Qh),I4=Yt(Va,P4,Eu,L4,Qh),U9=Yt(Se(I4,De(477),be(re(421)))),wo=Re(U9),F9=Yt(Se(I4,De(478),be(re(421))),Se(I4,De(448),be(re(449)),De(477),be(re(421)))),Ai=Re(F9),$9=Se(Eu,De(280),be(re(466)),be(re(466)),be(re(421))),vu=Re($9),K9=Se(Qh,De(465),be(re(466)),be(re(466)),be(re(421))),D4=Re(K9),Wh=Yt(U9,F9,Se(P4,be(re(421))),Se(nO,be(re(421))),Se(Va,be(re(421))),$9,K9,re(421)),Ha=Re(Wh),oO=Se(be(Wh),De(290),L9(De(281)),be(re(421))),_t=Re(oO),sO=Yt(Se(Wh,De(290),De(281),be(re(421))),Se(Wh,De(281),be(re(421))),Se(De(281),be(re(421)))),Su=Re(sO),iO=Se(Va,Yt(Se(re(6,"80")),Se(re(6),De(480)),De(480)),be(re(481)),be(re(421))),V9=Re(iO),aO=Se(Va,Yt(Se(re(6,"443")),Se(re(6,"443"),De(480)),Se(re(6),De(443)),Se(re(6),De(448),De(480)),Se(De(448),De(480)),De(448),De(443)),be(re(481)),be(re(421))),H9=Re(aO),cO=Yt(Se(re(777),be(re(421)))),Vte=Re(cO),lO=Yt(Se(re(400),be(re(421)))),Hte=Re(lO);function q9(r,e){let t=Si.exactMatch(r),n=Si.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=Ai.exactMatch(r),s=Ai.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=wo.exactMatch(r),a=wo.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=Su.exactMatch(r),l=Su.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=vu.exactMatch(r),d=vu.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=D4.exactMatch(r),h=D4.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function z9(r,e){let t=pu(r),n=pu(e);return t&&!n?1:!t&&n?-1:0}function W9(r,e){let t=it(r),n=it(e);return t&&!n?1:!t&&n?-1:0}function G9(r,e){let t=_t.exactMatch(r),n=_t.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function qe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Jh=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}},qa=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Jh(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 Jh(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 R4=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Mt(r={}){return uO(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 uO(r,e){e=e??{};let t=e.onEnd,n=new qa,o,s,i,a=qe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,m)=>{s=w=>{s=null,n.push(w);try{g(r(n))}catch(x){m(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=qe()})}},l=g=>s!=null?s(g):(n.push(g),o),u=g=>(n=new qa,s!=null?s({error:g}):(n.push({error:g}),o)),d=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>i?o:(i=!0,g!=null?u(g):l({done:!0})),h=()=>(n=new qa,f(),{done:!0}),p=g=>(f(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async g=>{let m=g?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let w,x;m!=null&&(w=new Promise((E,S)=>{x=()=>{S(new R4)},m.addEventListener("abort",x)}));try{await Promise.race([a.promise,w])}finally{x!=null&&m!=null&&m?.removeEventListener("abort",x)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(g){return y.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:g=>y.onEmpty(g)},o}var N4=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},j9=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function cr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={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(j9(i));return}if(i&&(c=()=>{f(j9(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new N4;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var dO=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 fO(r,e,t){let n,o=new Promise((s,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}=dO(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=cr(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Yr(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=fO(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function bo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Zh=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}},e1=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Ii=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},t1=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},r1=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function hO(r){return r.reason}async function Ue(r,e,t){if(e==null)return r;let n=t?.translateError??hO;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var n1=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=qe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new nr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function pO(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var o1=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=pO(),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 nr),this.cleanup())}async join(e){let t=new n1(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 Ue(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){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.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var mt=class extends le{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=bo(this.emitEmpty.bind(this),1),this.emitIdle=bo(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 e1;let n=new o1(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new nr)}),this.clear()}async onEmpty(e){this.size!==0&&await Yr(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Yr(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Yr(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=Mt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new nr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var mO=Math.pow(2,20)*4,cs=class extends le{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??mO,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new Y,this.writeBuffer=new Y,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(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new r1)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ue(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Mt(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Nn(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new mh(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Nn("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 Nn("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 Nn(`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 Nn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new xa;this.dispatchEvent(new gh(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new es))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;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 o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new Y(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}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}}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 ph(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Vl(`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 Vl(`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 ls=class extends cs{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 Yr(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 Yr(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function s1(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var us=class extends le{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 o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}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 Ue(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 an;let t=this.onCreateStream({...this.streamOptions,...e});return s1(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 t1(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ds=class extends cs{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 Yr(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 Yr(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var za=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var gO=1.2,yO=2,wO=5e3,bO=6e4,xO=5e3,yn=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??xO;this.success=new za(t),this.failure=new za(t),this.next=new za(t),this.failureMultiplier=e.failureMultiplier??yO,this.timeoutMultiplier=e.timeoutMultiplier??gO,this.minTimeout=e.minTimeout??wO,this.maxTimeout=e.maxTimeout??bO,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=de([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var O4=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=qe(),this.haveNext=qe()}[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=qe(),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=qe(),await Ue(this.readNext.promise,t?.signal,t)}};function Y9(){return new O4}function EO(r){return r[Symbol.asyncIterator]!=null}async function vO(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*SO(r){let e=new AbortController,t=Y9();vO(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*AO(r){for(let e of r)yield*e}function IO(...r){let e=[];for(let t of r)EO(t)||e.push(t);return e.length===r.length?AO(e):SO(r)}var lr=IO;function Wa(r,...e){if(r==null)throw new Error("Empty pipeline");if(B4(r)){let n=r;r=()=>n.source}else if(Q9(r)||X9(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&B4(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++)B4(t[n])&&(t[n]=CO(t[n]));return TO(...t)}var TO=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},X9=r=>r?.[Symbol.asyncIterator]!=null,Q9=r=>r?.[Symbol.iterator]!=null,B4=r=>r==null?!1:r.sink!=null&&r.source!=null,CO=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Mt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(X9(s))o=async function*(){yield*s,n.end()};else if(Q9(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return lr(n,o())}return r.source};var kO=4194304,i1=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Au=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},U4=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},F4=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function _O(r){return typeof r?.closeRead=="function"}function PO(r){return typeof r?.close=="function"}function M4(r){return _O(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:PO(r)?r.status!=="open":!1}function LO(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function a1(r,e){let t=e?.maxBufferSize??kO,n=new Y,o,s=!1;if(!LO(r))throw new A("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new i1("Stream was unwrapped");if(M4(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Ii(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ue(o.promise,u?.signal),M4(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let f=u?.bytes??n.byteLength;if(n.byteLength<f){if(M4(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new Ii(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(u)}let h=n.sublist(0,f);return n.consume(f),h},async write(u,d){if(s===!0)throw new i1("Stream was unwrapped");r.send(u)||await Yr(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function fs(r,e={}){let t=a1(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=we(e.maxDataLength));let n=e?.lengthDecoder??_r,o=e?.lengthEncoder??Gt;return{async read(i){let a=-1,c=new Y;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 Au("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new F4(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new U4(`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 Ii(`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 Ii(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function We(r,e){let t=fs(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var DO=1024*1024*4,RO=1024*1024*4,c1=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new Y,this.maxBufferSize=e.maxBufferSize??DO,this.maxDataLength=e.maxDataLength??RO,this.lengthDecoder=e.lengthDecoder??_r,this.encodingLength=e.encodingLength??we}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new A(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(t<0||t>this.maxDataLength)throw new Au("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var NO=["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 $4(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=OO(r);return t||"Object"}function OO(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(NO.includes(e))return e}var b=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}};b.uint=new b(0,"uint",!0);b.negint=new b(1,"negint",!0);b.bytes=new b(2,"bytes",!0);b.string=new b(3,"string",!0);b.array=new b(4,"array",!1);b.map=new b(5,"map",!1);b.tag=new b(6,"tag",!1);b.float=new b(7,"float",!0);b.false=new b(7,"false",!0);b.true=new b(7,"true",!0);b.null=new b(7,"null",!0);b.undefined=new b(7,"undefined",!0);b.break=new b(7,"break",!0);var B=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 Iu=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",BO=new TextEncoder;function l1(r){return Iu&&globalThis.Buffer.isBuffer(r)}function Ti(r){return r instanceof Uint8Array?l1(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var MO=24,UO=200,Ga=Iu?r=>r.length>=MO?globalThis.Buffer.from(r):J9(r):r=>r.length>=UO?BO.encode(r):J9(r),Fn=r=>Uint8Array.from(r),ex=Iu?(r,e,t)=>l1(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),tx=Iu?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Ti(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},rx=Iu?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function u1(r,e){if(l1(r)&&l1(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 J9(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var Z9=4096;function nx(r){let e=r.length;if(e<=Z9)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Z9));return t}var FO=256,Tu=class{constructor(e=FO){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=rx(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=ex(n,0,this.cursor)}else t=tx(this.chunks,this.cursor);return e&&this.reset(),t}},d1=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var W="CBOR decode error:",$n="CBOR encode error:",Cu=[];Cu[23]=1;Cu[24]=2;Cu[25]=3;Cu[26]=5;Cu[27]=9;function xo(r,e,t){if(r.length-e<t)throw new Error(`${W} not enough data for type`)}var Pt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Lr(r,e,t){xo(r,e,1);let n=r[e];if(t.strict===!0&&n<Pt[0])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function Dr(r,e,t){xo(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Pt[1])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function Rr(r,e,t){xo(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Pt[2])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function Nr(r,e,t){xo(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<Pt[3])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${W} integers outside of the safe integer range are not supported`)}function ox(r,e,t,n){return new B(b.uint,Lr(r,e+1,n),2)}function sx(r,e,t,n){return new B(b.uint,Dr(r,e+1,n),3)}function ix(r,e,t,n){return new B(b.uint,Rr(r,e+1,n),5)}function ax(r,e,t,n){return new B(b.uint,Nr(r,e+1,n),9)}function Xr(r,e){return Ge(r,0,e.value)}function Ge(r,e,t){if(t<Pt[0]){let n=Number(t);r.push([e|n])}else if(t<Pt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Pt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Pt[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<Pt[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${W} encountered BigInt larger than allowable range`)}}Xr.encodedSize=function(e){return Ge.encodedSize(e.value)};Ge.encodedSize=function(e){return e<Pt[0]?1:e<Pt[1]?2:e<Pt[2]?3:e<Pt[3]?5:9};Xr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function cx(r,e,t,n){return new B(b.negint,-1-Lr(r,e+1,n),2)}function lx(r,e,t,n){return new B(b.negint,-1-Dr(r,e+1,n),3)}function ux(r,e,t,n){return new B(b.negint,-1-Rr(r,e+1,n),5)}var K4=BigInt(-1),dx=BigInt(1);function fx(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new B(b.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${W} integers outside of the safe integer range are not supported`);return new B(b.negint,K4-BigInt(o),9)}function f1(r,e){let t=e.value,n=typeof t=="bigint"?t*K4-dx:t*-1-1;Ge(r,e.type.majorEncoded,n)}f1.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*K4-dx:t*-1-1;return n<Pt[0]?1:n<Pt[1]?2:n<Pt[2]?3:n<Pt[3]?5:9};f1.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ku(r,e,t,n){xo(r,e,t+n);let o=r.slice(e+t,e+t+n);return new B(b.bytes,o,t+n)}function hx(r,e,t,n){return ku(r,e,1,t)}function px(r,e,t,n){return ku(r,e,2,Lr(r,e+1,n))}function mx(r,e,t,n){return ku(r,e,3,Dr(r,e+1,n))}function gx(r,e,t,n){return ku(r,e,5,Rr(r,e+1,n))}function yx(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer bytes lengths not supported`);return ku(r,e,9,o)}function h1(r){return r.encodedBytes===void 0&&(r.encodedBytes=b.equals(r.type,b.string)?Ga(r.value):r.value),r.encodedBytes}function ja(r,e){let t=h1(e);Ge(r,e.type.majorEncoded,t.length),r.push(t)}ja.encodedSize=function(e){let t=h1(e);return Ge.encodedSize(t.length)+t.length};ja.compareTokens=function(e,t){return KO(h1(e),h1(t))};function KO(r,e){return r.length<e.length?-1:r.length>e.length?1:u1(r,e)}var wx=new TextDecoder,HO=32;function qO(r,e,t){if(t-e<HO){let o="";for(let s=e;s<t;s++){let i=r[s];if(i&128)return wx.decode(r.subarray(e,t));o+=String.fromCharCode(i)}return o}return wx.decode(r.subarray(e,t))}function _u(r,e,t,n,o){let s=t+n;xo(r,e,s);let i=new B(b.string,qO(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=r.slice(e+t,e+s)),i}function bx(r,e,t,n){return _u(r,e,1,t,n)}function xx(r,e,t,n){return _u(r,e,2,Lr(r,e+1,n),n)}function Ex(r,e,t,n){return _u(r,e,3,Dr(r,e+1,n),n)}function vx(r,e,t,n){return _u(r,e,5,Rr(r,e+1,n),n)}function Sx(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer string lengths not supported`);return _u(r,e,9,o,n)}var Ax=ja;function Ya(r,e,t,n){return new B(b.array,n,t)}function Ix(r,e,t,n){return Ya(r,e,1,t)}function Tx(r,e,t,n){return Ya(r,e,2,Lr(r,e+1,n))}function Cx(r,e,t,n){return Ya(r,e,3,Dr(r,e+1,n))}function kx(r,e,t,n){return Ya(r,e,5,Rr(r,e+1,n))}function _x(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer array lengths not supported`);return Ya(r,e,9,o)}function Px(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Ya(r,e,1,1/0)}function p1(r,e){Ge(r,b.array.majorEncoded,e.value)}p1.compareTokens=Xr.compareTokens;p1.encodedSize=function(e){return Ge.encodedSize(e.value)};function Xa(r,e,t,n){return new B(b.map,n,t)}function Lx(r,e,t,n){return Xa(r,e,1,t)}function Dx(r,e,t,n){return Xa(r,e,2,Lr(r,e+1,n))}function Rx(r,e,t,n){return Xa(r,e,3,Dr(r,e+1,n))}function Nx(r,e,t,n){return Xa(r,e,5,Rr(r,e+1,n))}function Ox(r,e,t,n){let o=Nr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer map lengths not supported`);return Xa(r,e,9,o)}function Bx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Xa(r,e,1,1/0)}function m1(r,e){Ge(r,b.map.majorEncoded,e.value)}m1.compareTokens=Xr.compareTokens;m1.encodedSize=function(e){return Ge.encodedSize(e.value)};function Mx(r,e,t,n){return new B(b.tag,t,1)}function Ux(r,e,t,n){return new B(b.tag,Lr(r,e+1,n),2)}function Fx(r,e,t,n){return new B(b.tag,Dr(r,e+1,n),3)}function $x(r,e,t,n){return new B(b.tag,Rr(r,e+1,n),5)}function Kx(r,e,t,n){return new B(b.tag,Nr(r,e+1,n),9)}function g1(r,e){Ge(r,b.tag.majorEncoded,e.value)}g1.compareTokens=Xr.compareTokens;g1.encodedSize=function(e){return Ge.encodedSize(e.value)};var V4=20,H4=21,q4=22,z4=23;function Vx(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${W} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(b.null,null,1):new B(b.undefined,void 0,1)}function Hx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return new B(b.break,void 0,1)}function W4(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${W} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${W} Infinity values are not supported`)}return new B(b.float,r,e)}function qx(r,e,t,n){return W4(G4(r,e+1),3,n)}function zx(r,e,t,n){return W4(j4(r,e+1),5,n)}function Wx(r,e,t,n){return W4(Xx(r,e+1),9,n)}function Pu(r,e,t){let n=e.value;if(n===!1)r.push([b.float.majorEncoded|V4]);else if(n===!0)r.push([b.float.majorEncoded|H4]);else if(n===null)r.push([b.float.majorEncoded|q4]);else if(n===void 0)r.push([b.float.majorEncoded|z4]);else{let o,s=!1;(!t||t.float64!==!0)&&(jx(n),o=G4(wn,1),n===o||Number.isNaN(n)?(wn[0]=249,r.push(wn.slice(0,3)),s=!0):(Yx(n),o=j4(wn,1),n===o&&(wn[0]=250,r.push(wn.slice(0,5)),s=!0))),s||(YO(n),o=Xx(wn,1),wn[0]=251,r.push(wn.slice(0,9)))}}Pu.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){jx(n);let o=G4(wn,1);if(n===o||Number.isNaN(n))return 3;if(Yx(n),o=j4(wn,1),n===o)return 5}return 9};var Gx=new ArrayBuffer(9),Qr=new DataView(Gx,1),wn=new Uint8Array(Gx,0);function jx(r){if(r===1/0)Qr.setUint16(0,31744,!1);else if(r===-1/0)Qr.setUint16(0,64512,!1);else if(Number.isNaN(r))Qr.setUint16(0,32256,!1);else{Qr.setFloat32(0,r);let e=Qr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Qr.setUint16(0,31744,!1);else if(t===0)Qr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Qr.setUint16(0,0):o<-14?Qr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Qr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function G4(r,e){if(r.length-e<2)throw new Error(`${W} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function Yx(r){Qr.setFloat32(0,r,!1)}function j4(r,e){if(r.length-e<4)throw new Error(`${W} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function YO(r){Qr.setFloat64(0,r,!1)}function Xx(r,e){if(r.length-e<8)throw new Error(`${W} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Pu.compareTokens=Xr.compareTokens;function Ce(r,e,t){throw new Error(`${W} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function y1(r){return()=>{throw new Error(`${W} ${r}`)}}var q=[];for(let r=0;r<=23;r++)q[r]=Ce;q[24]=ox;q[25]=sx;q[26]=ix;q[27]=ax;q[28]=Ce;q[29]=Ce;q[30]=Ce;q[31]=Ce;for(let r=32;r<=55;r++)q[r]=Ce;q[56]=cx;q[57]=lx;q[58]=ux;q[59]=fx;q[60]=Ce;q[61]=Ce;q[62]=Ce;q[63]=Ce;for(let r=64;r<=87;r++)q[r]=hx;q[88]=px;q[89]=mx;q[90]=gx;q[91]=yx;q[92]=Ce;q[93]=Ce;q[94]=Ce;q[95]=y1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)q[r]=bx;q[120]=xx;q[121]=Ex;q[122]=vx;q[123]=Sx;q[124]=Ce;q[125]=Ce;q[126]=Ce;q[127]=y1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)q[r]=Ix;q[152]=Tx;q[153]=Cx;q[154]=kx;q[155]=_x;q[156]=Ce;q[157]=Ce;q[158]=Ce;q[159]=Px;for(let r=160;r<=183;r++)q[r]=Lx;q[184]=Dx;q[185]=Rx;q[186]=Nx;q[187]=Ox;q[188]=Ce;q[189]=Ce;q[190]=Ce;q[191]=Bx;for(let r=192;r<=215;r++)q[r]=Mx;q[216]=Ux;q[217]=Fx;q[218]=$x;q[219]=Kx;q[220]=Ce;q[221]=Ce;q[222]=Ce;q[223]=Ce;for(let r=224;r<=243;r++)q[r]=y1("simple values are not supported");q[244]=Ce;q[245]=Ce;q[246]=Ce;q[247]=Vx;q[248]=y1("simple values are not supported");q[249]=qx;q[250]=zx;q[251]=Wx;q[252]=Ce;q[253]=Ce;q[254]=Ce;q[255]=Hx;var bn=[];for(let r=0;r<24;r++)bn[r]=new B(b.uint,r,1);for(let r=-1;r>=-24;r--)bn[31-r]=new B(b.negint,r,1);bn[64]=new B(b.bytes,new Uint8Array(0),1);bn[96]=new B(b.string,"",1);bn[128]=new B(b.array,0,1);bn[160]=new B(b.map,0,1);bn[244]=new B(b.false,!1,1);bn[245]=new B(b.true,!0,1);bn[246]=new B(b.null,null,1);function Y4(r){switch(r.type){case b.false:return Fn([244]);case b.true:return Fn([245]);case b.null:return Fn([246]);case b.bytes:return r.value.length?void 0:Fn([64]);case b.string:return r.value===""?Fn([96]):void 0;case b.array:return r.value===0?Fn([128]):void 0;case b.map:return r.value===0?Fn([160]):void 0;case b.uint:return r.value<24?Fn([Number(r.value)]):void 0;case b.negint:if(r.value>=-24)return Fn([31-Number(r.value)])}}var QO={float64:!1,mapSorter:eB,quickEncodeToken:Y4},tE=Object.freeze({mapSorter:tB,quickEncodeToken:Y4});function JO(){let r=[];return r[b.uint.major]=Xr,r[b.negint.major]=f1,r[b.bytes.major]=ja,r[b.string.major]=Ax,r[b.array.major]=p1,r[b.map.major]=m1,r[b.tag.major]=g1,r[b.float.major]=Pu,r}var Ja=JO(),w1=new Tu,Du=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(`${$n} object contains circular references`);return new r(t,e)}},hs={null:new B(b.null,null),undefined:new B(b.undefined,void 0),true:new B(b.true,!0),false:new B(b.false,!1),emptyArray:new B(b.array,0),emptyMap:new B(b.map,0)},Kn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new B(b.float,r):r>=0?new B(b.uint,r):new B(b.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new B(b.uint,r):new B(b.negint,r)},Uint8Array(r,e,t,n){return new B(b.bytes,r)},string(r,e,t,n){return new B(b.string,r)},boolean(r,e,t,n){return r?hs.true:hs.false},null(r,e,t,n){return hs.null},undefined(r,e,t,n){return hs.undefined},ArrayBuffer(r,e,t,n){return new B(b.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new B(b.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[hs.emptyArray,new B(b.break)]:hs.emptyArray;n=Du.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Qa(i,t,n);return t.addBreakTokens?[new B(b.array,r.length),o,new B(b.break)]:[new B(b.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length,a;if(i){a=new Array(i),n=Du.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of s){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[Qa(u,t,n),Qa(d,t,n)])}l<i&&(a.length=l)}return a?.length?(ZO(a,t),t.addBreakTokens?[new B(b.map,a.length),a,new B(b.break)]:[new B(b.map,a.length),a]):t.addBreakTokens===!0?[hs.emptyMap,new B(b.break)]:hs.emptyMap},Tagged(r,e,t,n){return[new B(b.tag,r.tag),Qa(r.value,t,n)]}};Kn.Map=Kn.Object;Kn.Buffer=Kn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Kn[`${r}Array`]=Kn.DataView;function Qa(r,e={},t){let n=$4(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Kn[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=Kn[n];if(!s)throw new Error(`${$n} unsupported type: ${n}`);return s(r,n,e,t)}function ZO(r,e){e.mapSorter&&r.sort(e.mapSorter)}function eB(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=Ja[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function tB(r,e){if(r[0]instanceof B&&e[0]instanceof B){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Qx(t.value)),n._keyBytes||(n._keyBytes=Qx(n.value)),u1(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Qx(r){return b1(r,Ja,tE)}function Lu(r,e,t,n){if(Array.isArray(e))for(let o of e)Lu(r,o,t,n);else t[e.type.major](r,e,n)}var Jx=b.uint.majorEncoded,Zx=b.negint.majorEncoded,rB=b.bytes.majorEncoded,nB=b.string.majorEncoded,eE=b.array.majorEncoded,oB=b.float.majorEncoded|V4,sB=b.float.majorEncoded|H4,iB=b.float.majorEncoded|q4,aB=b.float.majorEncoded|z4,cB=BigInt(-1),lB=BigInt(1);function uB(r){return r.addBreakTokens!==!0}function rE(r,e,t,n){let o=$4(e),s=t.typeEncoders&&t.typeEncoders[o];if(s){let i=s(e,o,t,n);if(i!=null){Lu(r,i,Ja,t);return}}switch(o){case"null":r.push([iB]);return;case"undefined":r.push([aB]);return;case"boolean":r.push([e?sB:oB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Pu(r,new B(b.float,e),t):e>=0?Ge(r,Jx,e):Ge(r,Zx,e*-1-1);return;case"bigint":e>=BigInt(0)?Ge(r,Jx,e):Ge(r,Zx,e*cB-lB);return;case"string":{let i=Ga(e);Ge(r,nB,i.length),r.push(i);return}case"Uint8Array":Ge(r,rB,e.length),r.push(e);return;case"Array":if(!e.length){r.push([eE]);return}n=Du.createCheck(n,e),Ge(r,eE,e.length);for(let i of e)rE(r,i,t,n);return;case"Object":case"Map":{let i=Kn.Object(e,o,t,n);Lu(r,i,Ja,t)}return;default:{let i=Kn[o];if(!i)throw new Error(`${$n} unsupported type: ${o}`);let a=i(e,o,t,n);Lu(r,a,Ja,t)}}}function b1(r,e,t,n){let o=n instanceof Uint8Array,s=o?new d1(n):w1,i=Qa(r,t);if(!Array.isArray(i)&&t.quickEncodeToken){let a=t.quickEncodeToken(i);if(a)return o?(s.push(a),s.toBytes()):a;let c=e[i.type.major];if(c.encodedSize){let l=c.encodedSize(i,t);if(o||(s=new Tu(l)),c(s,i,t),s.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${i} was wrong`);return o?s.toBytes():Ti(s.chunks[0])}}return s.reset(),Lu(s,i,e,t),s.toBytes(!0)}function ki(r,e){return e=Object.assign({},QO,e),uB(e)?(w1.reset(),rE(w1,r,e,void 0),w1.toBytes(!0)):b1(r,Ja,e)}var dB={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},x1=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=bn[e];if(t===void 0){let n=q[e];if(!n)throw new Error(`${W} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},ps=Symbol.for("DONE"),Za=Symbol.for("BREAK");function fB(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=ms(e,t);if(s===Za){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed array`)}if(s===ps)throw new Error(`${W} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function hB(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,s=n?void 0:{},i=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=ms(e,t);if(c===Za){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(c===ps)throw new Error(`${W} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${W} non-string keys not supported (got ${typeof c})`);if(o&&(n&&i.has(c)||!n&&Object.hasOwn(s,c)))throw new Error(`${W} found repeat map key "${c}"`);let l=ms(e,t);if(l===ps)throw new Error(`${W} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?i.set(c,l):s[c]=l}return n?i:s}function*pB(r,e,t){for(let n=0;n<r.value;n++){let o=ms(e,t);if(o===Za){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(o===ps)throw new Error(`${W} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let s=ms(e,t);if(s===ps)throw new Error(`${W} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,s]}}function mB(r,e){let t=!1,n=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=ms(r,e);if(o===ps)throw new Error(`${W} tag content missing`);if(o===Za)throw new Error(`${W} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=r.next();if(!b.equals(o.type,b.map))throw new Error(`${W} entries() requires map content, got ${o.type.name}`);let s=[];for(let i of pB(o,r,e))s.push(i);return s},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ms(r,e){if(r.done())return ps;let t=r.next();if(b.equals(t.type,b.break))return Za;if(t.type.terminal)return t.value;if(b.equals(t.type,b.array))return fB(t,r,e);if(b.equals(t.type,b.map))return hB(t,r,e);if(b.equals(t.type,b.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=mB(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${W} tag decoder must call decode() or entries()`);return o}throw new Error(`${W} tag not supported (${t.value})`)}throw new Error("unsupported")}function X4(r,e){if(!(r instanceof Uint8Array))throw new Error(`${W} data to decode must be a Uint8Array`);e=Object.assign({},dB,e);let t=Ti(r),n=e.tokenizer||new x1(t,e),o=ms(n,e);if(o===ps)throw new Error(`${W} did not find any content to decode`);if(o===Za)throw new Error(`${W} got unexpected break`);return[o,r.subarray(n.pos())]}function xn(r,e){let[t,n]=X4(r,e);if(n.length>0)throw new Error(`${W} too many terminals, data makes no sense`);return t}var E1=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(E1.prototype,Symbol.toStringTag,{value:"Tagged"});var v1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ec=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},S1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Ru=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function A1(r){return r[Symbol.asyncIterator]!=null}function oE(r,e){if(r.byteLength>e)throw new ec("Message length too long")}var T1=r=>{let e=we(r),t=st(e);return Gt(r,t),T1.bytes=e,t};T1.bytes=0;function Eo(r,e){e=e??{};let t=e.lengthEncoder??T1,n=e?.maxDataLength??4194304;function*o(s){oE(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return A1(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Eo.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??T1,n=e?.maxDataLength??4194304;return oE(r,n),new Y(t(r.byteLength),r)};var _i;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_i||(_i={}));var Q4=r=>{let e=_r(r);return Q4.bytes=we(e),e};Q4.bytes=0;function Pi(r,e){let t=new Y,n=_i.LENGTH,o=-1,s=e?.lengthDecoder??Q4,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===_i.LENGTH)try{if(o=s(t),o<0)throw new v1("Invalid message length");if(o>a)throw new ec("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=_i.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new S1("Message length length too long");break}throw l}if(n===_i.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=_i.LENGTH}}}return A1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Ru("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Ru("Unexpected end of input")})()}Pi.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Pi(n,{...e??{},onLength:s=>{t=s}})};function C1(r,e){if(typeof r=="string")return yB(r);if(typeof r=="number")return xB(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function yB(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,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function wB(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 bB(r){let e=Math.abs(r);return e>=315576e5?Li(r,e,315576e5,"year"):e>=26298e5?Li(r,e,26298e5,"month"):e>=6048e5?Li(r,e,6048e5,"week"):e>=864e5?Li(r,e,864e5,"day"):e>=36e5?Li(r,e,36e5,"hour"):e>=6e4?Li(r,e,6e4,"minute"):e>=1e3?Li(r,e,1e3,"second"):`${r} ms`}function xB(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?bB(r):wB(r)}function Li(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function J4(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=C1,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,y;function g(...m){if(!g.enabled)return;let w=g,x=Number(new Date),E=x-(f||x);w.diff=E,w.prev=f,w.curr=x,f=x,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let S=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(I,C)=>{if(I==="%%")return"%";S++;let U=t.formatters[C];if(typeof U=="function"){let j=m[S];I=U.call(w,j),m.splice(S,1),S--}return I}),t.formatArgs.call(w,m),d?.onLog!=null&&d.onLog(...m),(w.log||t.log).apply(w,m)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:m=>{h=m}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){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 k1=CB(),EB=["#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 vB(){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 SB(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+C1(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var AB=console.debug??console.log??(()=>{});function IB(r){try{r?k1?.setItem("debug",r):k1?.removeItem("debug")}catch{}}function TB(){let r;try{r=k1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function CB(){try{return localStorage}catch{}}function kB(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var iE=J4({formatArgs:SB,save:IB,load:TB,useColors:vB,setupFormatters:kB,colors:EB,storage:k1,log:AB});var je=iE;je.formatters.b=r=>r==null?"undefined":ge.baseEncode(r);je.formatters.t=r=>r==null?"undefined":pt.baseEncode(r);je.formatters.m=r=>r==null?"undefined":$e.baseEncode(r);je.formatters.p=r=>r==null?"undefined":r.toString();je.formatters.c=r=>r==null?"undefined":r.toString();je.formatters.k=r=>r==null?"undefined":r.toString();je.formatters.a=r=>r==null?"undefined":r.toString();function aE(r,e=""){let t=cE(r.message),n=cE(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 _B(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function lE(r,e=""){if(_B(r)){let t=aE(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
10
10
|
${e}${r.errors.map(n=>`${lE(n,`${e}`)}`).join(`
|
|
11
11
|
${e}`)}`):t+=`
|
|
12
|
-
${e}[Error list was empty]`,t.trim()}return aE(r,e)}je.formatters.e=r=>r==null?"undefined":lE(r);function PB(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 tc(r){return{forComponent(e){return rc(e,r)}}}function rc(r,e){let t=PB(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=je(`${r}:trace`,e)),Object.assign(je(r,e),{error:je(`${r}:error`,e),trace:t,newScope:n=>rc(`${r}:${n}`,e)})}function cE(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var uE=Symbol.for("sindresorhus/unlimited-timeout#brand");function dE(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[uE]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let s=performance.now()+e,i=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||r(...t)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,s-c);i(l)},2147483647),n&&o.id?.unref?.()))};return i(e),o}function fE(r){!r||typeof r!="object"||!r[uE]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var LB=new WeakMap;function DB({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(o.reason)},u=()=>{o&&o.removeEventListener("abort",l)},d=new Promise((f,h)=>{i=()=>{u(),f(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",l,{once:!0}),LB.set(d,()=>{c(s),s=null,i()}),d}}var RB=DB({setTimeout:dE,clearTimeout:fE}),hE=RB;var Xt=class extends mt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var _1=class extends mt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var nc=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 Z4}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);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(o,i.consumedPoints,this.blockDuration)),new Zh("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,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)}},Z4=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,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 oc(r,e,t){let n,o,s=!1;function i(){let l={signal:o.signal},u;t?.timeout!=null&&(u=de([o.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),s=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,!o.signal.aborted&&(n=setTimeout(i,e))})}let a=bo(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:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var e6=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 gt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new e6({name:e,metrics:t}):n=new Map,n}var sc=class extends le{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=Nt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=$e.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=qe(),i={promise:s.promise,observers:1,queryFilter:Nt(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 mt({concurrency:this.maxProviders});l.addEventListener("failure",f=>{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,s.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)];this.evict(h)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),s.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 Ue(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&&s.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=()=>{s.reject(new nr(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await s.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 o=qe(),s=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",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.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",s,t,this.providers.length),this.providers.length<t)throw new au(`Found ${s} 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),o.reject(i)}),o.promise}};var P1=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Nu=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},L1=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},vo=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},D1=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},R1=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Ou=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};function NB(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ic=NB;function OB(r){return r[Symbol.asyncIterator]!=null}function BB(r,e){let t=0;if(OB(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=ic(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Br=BB;function MB(r){return r[Symbol.asyncIterator]!=null}function UB(r){if(MB(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ke([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ke(e,t)}var N1=UB;function O1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*FB(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],s=K.asCID(n);s!=null?yield[o.join("/"),s]:typeof n=="object"&&(yield*t6(n,o))}else{let t=K.asCID(e);t!=null?yield[r.join("/"),t]:yield*t6(e,r)}}function*t6(r,e){if(r==null||r instanceof Uint8Array)return;let t=K.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let s=[...e,n];yield*FB(s,o)}}function*$B(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&K.asCID(n)==null&&(yield*r6(n,o))}else yield*r6(e,r)}function*r6(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&K.asCID(n)==null&&(yield*$B(o,n))}}function KB(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=K.asCID(t);if(s!=null)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}var n6=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:O1(),bytes:O1(),value:O1(),asBlock:O1()})}links(){return t6(this.value,[])}tree(){return r6(this.value,[])}get(e="/"){return KB(this.value,e.split("/").filter(Boolean))}};function pE({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new n6({cid:e,bytes:r,value:o})}function i6(r){return e=>new s6(e,r)}var o6=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),o=Br(n.toGenerator(t),c=>c!=null),s=!1,i=t?.depth??1/0,a=async c=>{let l=c.cid,u=await N1(this.components.blockstore.get(l,c)),d=pE({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=>{s||o.throw(h)});return{block:d,depth:c.depth,path:c.path}};n.add(a,{...t,cid:e,depth:0,path:[e]}).catch(c=>{s||o.throw(c)});try{yield*o}finally{s=!0,n.abort()}}},s6=class extends o6{getQueue(){return new mt({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}};function ac(r){return r==null?!1:K.asCID(r)!=null}function gs(r){return r?.then!=null}var mE="1.2.840.10045.3.1.7",gE="1.3.132.0.34",yE="1.3.132.0.35";async function wE(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 bE(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,ee(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function xE(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,ee(e),ee(t.subarray()));return n?.signal?.throwIfAborted(),s}var VB=parseInt("11111",2),a6=parseInt("10000000",2),HB=parseInt("01111111",2),EE={0:Bu,1:Bu,2:qB,3:GB,4:jB,5:WB,6:zB,16:Bu,22:Bu,48:Bu};function Jr(r,e={offset:0}){let t=r[e.offset]&VB;if(e.offset++,EE[t]!=null)return EE[t](r,e);throw new Error("No decoder for tag "+t)}function Mu(r,e){let t=0;if((r[e.offset]&a6)===a6){let n=r[e.offset]&HB,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Bu(r,e){Mu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Jr(r,e);if(n===null)break;t.push(n)}return t}function qB(r,e){let t=Mu(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function zB(r,e){let t=Mu(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${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 WB(r,e){return e.offset++,null}function GB(r,e){let t=Mu(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function jB(r,e){let t=Mu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function YB(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function B1(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=YB(r.byteLength);return new Y(Uint8Array.from([e.byteLength|a6]),e)}function ur(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),B1(e),e)}function Uu(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),B1(t),t)}function vE(r){return new Y(Uint8Array.from([4]),B1(r),r)}function En(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),B1(t),t)}var XB=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),QB=Uint8Array.from([6,5,43,129,4,0,34]),JB=Uint8Array.from([6,5,43,129,4,0,35]),SE={ext:!0,kty:"EC",crv:"P-256"},AE={ext:!0,kty:"EC",crv:"P-384"},IE={ext:!0,kty:"EC",crv:"P-521"},cc=32,lc=48,uc=66;function TE(r){let e=Jr(r);return c6(e)}function c6(r){let e=r[1],t=M(e,"base64url"),n=r[2][1][0],o=1,s,i;if(e.byteLength===cc)return s=M(n.subarray(o,o+cc),"base64url"),i=M(n.subarray(o+cc),"base64url"),new Ri({...SE,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===lc)return s=M(n.subarray(o,o+lc),"base64url"),i=M(n.subarray(o+lc),"base64url"),new Ri({...AE,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===uc)return s=M(n.subarray(o,o+uc),"base64url"),i=M(n.subarray(o+uc),"base64url"),new Ri({...IE,key_ops:["sign"],d:t,x:s,y:i});throw new A(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function l6(r){let e=Jr(r);return CE(e)}function CE(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===cc*2+1)return n=M(e.subarray(t,t+cc),"base64url"),o=M(e.subarray(t+cc),"base64url"),new Di({...SE,key_ops:["verify"],x:n,y:o});if(e.byteLength===lc*2+1)return n=M(e.subarray(t,t+lc),"base64url"),o=M(e.subarray(t+lc),"base64url"),new Di({...AE,key_ops:["verify"],x:n,y:o});if(e.byteLength===uc*2+1)return n=M(e.subarray(t,t+uc),"base64url"),o=M(e.subarray(t+uc),"base64url"),new Di({...IE,key_ops:["verify"],x:n,y:o});throw new A(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function kE(r){return En([ur(Uint8Array.from([1])),vE(O(r.d??"","base64url")),En([PE(r.crv)],160),En([Uu(new Y(Uint8Array.from([4]),O(r.x??"","base64url"),O(r.y??"","base64url")))],161)]).subarray()}function _E(r){return En([ur(Uint8Array.from([1])),En([PE(r.crv)],160),En([Uu(new Y(Uint8Array.from([4]),O(r.x??"","base64url"),O(r.y??"","base64url")))],161)]).subarray()}function PE(r){if(r==="P-256")return XB;if(r==="P-384")return QB;if(r==="P-521")return JB;throw new A(`Invalid curve ${r}`)}async function LE(r="P-256"){let e=await wE(r);return new Ri(e.privateKey)}var Di=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=_E(this.jwk)),this._raw}toMultihash(){return Ze.digest(Lt(this))}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async verify(e,t,n){return xE(this.jwk,t,e,n)}},Ri=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Di({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=kE(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async sign(e,t){return bE(this.jwk,e,t)}};function u6(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function xr(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ut(r,e,t=""){let n=u6(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Ao(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(xr(r.outputLen),xr(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function dc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function M1(r,e){Ut(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Qt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ni(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function vn(r,e){return r<<32-e|r>>>e}function U1(r,e){return r<<e|r>>>32-e>>>0}var RE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ZB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function F1(r){if(Ut(r),RE)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=ZB[r[t]];return e}var So={_0:48,_9:57,A:65,F:70,a:97,f:102};function DE(r){if(r>=So._0&&r<=So._9)return r-So._0;if(r>=So.A&&r<=So.F)return r-(So.A-10);if(r>=So.a&&r<=So.f)return r-(So.a-10)}function Fu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(RE)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=DE(r.charCodeAt(s)),a=DE(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}var eM=async()=>{};async function NE(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await eM(),n+=s)}}function tM(r){if(typeof r!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function d6(r,e=""){return typeof r=="string"?tM(r):Ut(r,void 0,e)}function f6(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ut(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function OE(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new TypeError("options must be object or undefined");return Object.assign(r,e)}function $u(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function BE(r=32){xr(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 h6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function $1(r,e,t){return r&e^~r&t}function K1(r,e,t){return r&e^r&t^e&t}var Oi=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ni(this.buffer)}update(e){dc(this),Ut(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Ni(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dc(this),M1(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Qt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ni(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Io=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ft=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var V1=BigInt(4294967295),ME=BigInt(32);function rM(r,e=!1){return e?{h:Number(r&V1),l:Number(r>>ME&V1)}:{h:Number(r>>ME&V1)|0,l:Number(r&V1)|0}}function UE(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=rM(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var p6=(r,e,t)=>r>>>t,m6=(r,e,t)=>r<<32-t|e>>>t,Bi=(r,e,t)=>r>>>t|e<<32-t,Mi=(r,e,t)=>r<<32-t|e>>>t,Ku=(r,e,t)=>r<<64-t|e>>>t-32,Vu=(r,e,t)=>r>>>t-32|e<<64-t;function Vn(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var FE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),$E=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,KE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),VE=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,HE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),qE=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var oM=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]),ys=new Uint32Array(64),g6=class extends Oi{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)ys[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=ys[d-15],h=ys[d-2],p=vn(f,7)^vn(f,18)^f>>>3,y=vn(h,17)^vn(h,19)^h>>>10;ys[d]=y+ys[d-7]+p+ys[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=vn(a,6)^vn(a,11)^vn(a,25),h=u+f+$1(a,c,l)+oM[d]+ys[d]|0,y=(vn(n,2)^vn(n,13)^vn(n,22))+K1(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+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,o,s,i,a,c,l,u)}roundClean(){Qt(ys)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Qt(this.buffer)}},y6=class extends g6{A=Io[0]|0;B=Io[1]|0;C=Io[2]|0;D=Io[3]|0;E=Io[4]|0;F=Io[5]|0;G=Io[6]|0;H=Io[7]|0;constructor(){super(32)}};var zE=UE(["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))),sM=zE[0],iM=zE[1],ws=new Uint32Array(80),bs=new Uint32Array(80),w6=class extends Oi{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:y,Hl:g}=this;return[e,t,n,o,s,i,a,c,l,u,d,f,h,p,y,g]}set(e,t,n,o,s,i,a,c,l,u,d,f,h,p,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|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=y|0,this.Hl=g|0}process(e,t){for(let x=0;x<16;x++,t+=4)ws[x]=e.getUint32(t),bs[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let E=ws[x-15]|0,S=bs[x-15]|0,T=Bi(E,S,1)^Bi(E,S,8)^p6(E,S,7),I=Mi(E,S,1)^Mi(E,S,8)^m6(E,S,7),C=ws[x-2]|0,U=bs[x-2]|0,j=Bi(C,U,19)^Ku(C,U,61)^p6(C,U,6),z=Mi(C,U,19)^Vu(C,U,61)^m6(C,U,6),v=KE(I,z,bs[x-7],bs[x-16]),D=VE(v,T,j,ws[x-7],ws[x-16]);ws[x]=D|0,bs[x]=v|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:y,Gl:g,Hh:m,Hl:w}=this;for(let x=0;x<80;x++){let E=Bi(d,f,14)^Bi(d,f,18)^Ku(d,f,41),S=Mi(d,f,14)^Mi(d,f,18)^Vu(d,f,41),T=d&h^~d&y,I=f&p^~f&g,C=HE(w,S,I,iM[x],bs[x]),U=qE(C,m,E,T,sM[x],ws[x]),j=C|0,z=Bi(n,o,28)^Ku(n,o,34)^Ku(n,o,39),v=Mi(n,o,28)^Vu(n,o,34)^Vu(n,o,39),D=n&s^n&a^s&a,L=o&i^o&c^i&c;m=y|0,w=g|0,y=h|0,g=p|0,h=d|0,p=f|0,{h:d,l:f}=Vn(l|0,u|0,U|0,j|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=FE(j,v,L);n=$E(_,U,z,D),o=_|0}({h:n,l:o}=Vn(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Vn(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Vn(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Vn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Vn(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=Vn(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:g}=Vn(this.Gh|0,this.Gl|0,y|0,g|0),{h:m,l:w}=Vn(this.Hh|0,this.Hl|0,m|0,w|0),this.set(n,o,s,i,a,c,l,u,d,f,h,p,y,g,m,w)}roundClean(){Qt(ws,bs)}destroy(){this.destroyed=!0,Qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},b6=class extends w6{Ah=Ft[0]|0;Al=Ft[1]|0;Bh=Ft[2]|0;Bl=Ft[3]|0;Ch=Ft[4]|0;Cl=Ft[5]|0;Dh=Ft[6]|0;Dl=Ft[7]|0;Eh=Ft[8]|0;El=Ft[9]|0;Fh=Ft[10]|0;Fl=Ft[11]|0;Gh=Ft[12]|0;Gl=Ft[13]|0;Hh=Ft[14]|0;Hl=Ft[15]|0;constructor(){super(64)}};var Zr=$u(()=>new y6,h6(1));var Hn=$u(()=>new b6,h6(3));var ye=(r,e,t)=>Ut(r,e,t),E6=xr,fc=F1,xt=(...r)=>f6(...r),hc=r=>Fu(r),Ui=u6,Fi=r=>BE(r),q1=BigInt(0),x6=BigInt(1);function Sn(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function z1(r){if(typeof r=="bigint"){if(!H1(r))throw new RangeError("positive bigint expected, got "+r)}else E6(r);return r}function An(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 Hu(r){let e=z1(r).toString(16);return e.length&1?"0"+e:e}function WE(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?q1:BigInt("0x"+r)}function $i(r){return WE(F1(r))}function Mr(r){return WE(F1(xs(Ut(r)).reverse()))}function W1(r,e){if(xr(e),e===0)throw new RangeError("zero length");r=z1(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Fu(t.padStart(e*2,"0"))}function qu(r,e){return W1(r,e).reverse()}function GE(r,e){if(r=ye(r),e=ye(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function xs(r){return Uint8Array.from(ye(r))}function G1(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var H1=r=>typeof r=="bigint"&&q1<=r;function aM(r,e,t){return H1(r)&&H1(e)&&H1(t)&&e<=r&&r<t}function To(r,e,t,n){if(!aM(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function pc(r){if(r<q1)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>q1;r>>=x6,e+=1);return e}var zu=r=>(x6<<BigInt(r))-x6;function jE(r,e,t){if(xr(r,"hashLen"),xr(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),s=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=(...g)=>t(l,xt(c,...g)),h=(g=o)=>{l=f(s,g),c=f(),g.length!==0&&(l=f(i,g),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,m=[];for(;g<e;){c=f();let w=c.slice();m.push(w),g+=c.length}return xt(...m)};return(g,m)=>{d(),h(g);let w;for(;(w=m(p()))===void 0;)h();return d(),w}}function Ur(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var v6=()=>{throw new Error("not implemented")};var $t=BigInt(0),at=BigInt(1),Ki=BigInt(2),JE=BigInt(3),ZE=BigInt(4),ev=BigInt(5),cM=BigInt(7),tv=BigInt(8),lM=BigInt(9),rv=BigInt(16);function tt(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 Ye(r,e,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 YE(r,e){if(r===$t)throw new Error("invert: expected non-zero number");if(e<=$t)throw new Error("invert: expected positive modulus, got "+e);let t=tt(r,e),n=e,o=$t,s=at,i=at,a=$t;for(;t!==$t;){let l=n/t,u=n-t*l,d=o-i*l,f=s-a*l;n=t,t=u,o=i,s=a,i=d,a=f}if(n!==at)throw new Error("invert: does not exist");return tt(o,e)}function S6(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function nv(r,e){let t=r,n=(t.ORDER+at)/ZE,o=t.pow(e,n);return S6(t,o,e),o}function uM(r,e){let t=r,n=(t.ORDER-ev)/tv,o=t.mul(e,Ki),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Ki),s),c=t.mul(i,t.sub(a,t.ONE));return S6(t,c,e),c}function dM(r){let e=mc(r),t=ov(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+cM)/rv;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,n),f=l.mul(u,o),h=l.mul(u,s),p=l.eql(l.sqr(d),c),y=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,y);let g=l.eql(l.sqr(d),c),m=l.cmov(u,d,g);return S6(l,m,c),m})}function ov(r){if(r<JE)throw new Error("sqrt is not defined for small field");let e=r-at,t=0;for(;e%Ki===$t;)e/=Ki,t++;let n=Ki,o=mc(r);for(;XE(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return nv;let s=o.pow(n,e),i=(e+at)/Ki;return function(c,l){let u=c;if(u.is0(l))return l;if(XE(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,s),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let y=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(y++,g=u.sqr(g),y===d)throw new Error("Cannot find square root");let m=at<<BigInt(d-y-1),w=u.pow(f,m);d=y,f=u.sqr(w),h=u.mul(h,f),p=u.mul(p,w)}return p}}function fM(r){return r%ZE===JE?nv:r%tv===ev?uM:r%rv===lM?dM(r):ov(r)}var Co=(r,e)=>(tt(r,e)&at)===at,hM=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function A6(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=hM.reduce((n,o)=>(n[o]="function",n),e);if(Ur(r,t),An(r.BYTES,"BYTES"),An(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=at)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function pM(r,e,t){let n=r;if(t<$t)throw new Error("invalid exponent, negatives unsupported");if(t===$t)return n.ONE;if(t===at)return e;let o=n.ONE,s=e;for(;t>$t;)t&at&&(o=n.mul(o,s)),s=n.sqr(s),t>>=at;return o}function Wu(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function XE(r,e){let t=r,n=(t.ORDER-at)/Ki,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function mM(r,e){if(e!==void 0&&E6(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=pc(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var QE=new WeakMap,j1=class{ORDER;BITS;BYTES;isLE;ZERO=$t;ONE=at;_lengths;_mod;constructor(e,t={}){if(e<=at)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=mM(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return tt(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&at)===at}neg(e){return tt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return tt(e*e,this.ORDER)}add(e,t){return tt(e+t,this.ORDER)}sub(e,t){return tt(e-t,this.ORDER)}mul(e,t){return tt(e*t,this.ORDER)}pow(e,t){return pM(this,e,t)}div(e,t){return tt(e*YE(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 YE(e,this.ORDER)}sqrt(e){let t=QE.get(this);return t||QE.set(this,t=fM(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?qu(e,this.BYTES):W1(e,this.BYTES)}fromBytes(e,t=!1){ye(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Mr(e):$i(e);if(a&&(c=tt(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Wu(this,e)}cmov(e,t,n){return Sn(n,"condition"),n?t:e}};Object.freeze(j1.prototype);function mc(r,e={}){return new j1(r,e)}function sv(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=at)throw new Error("field order must be greater than 1");let e=pc(r-at);return Math.ceil(e/8)}function I6(r){let e=sv(r);return e+Math.ceil(e/2)}function T6(r,e,t=!1){ye(r);let n=r.length,o=sv(e),s=Math.max(I6(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Mr(r):$i(r),a=tt(i,e-at)+at;return t?qu(a,o):W1(a,o)}var gc=BigInt(0),Vi=BigInt(1);function Gu(r,e){let t=e.negate();return r?t:e}function Hi(r,e){let t=Wu(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function lv(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function C6(r,e){lv(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=zu(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function iv(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Vi);let l=e*n,u=l+Math.abs(a)-1,d=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:l}}var k6=new WeakMap,uv=new WeakMap;function _6(r){return uv.get(r)||1}function av(r){if(r!==gc)throw new Error("invalid wNAF")}var yc=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>gc;)t&Vi&&(n=n.add(o)),o=o.double(),t>>=Vi;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=C6(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=C6(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}=iv(n,a,i);n=c,u?s=s.add(Gu(f,t[h])):o=o.add(Gu(d,t[l]))}return av(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=C6(e,this.bits);for(let i=0;i<s.windows&&n!==gc;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=iv(n,i,s);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return av(n),o}getPrecomputes(e,t,n){let o=k6.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),k6.set(t,o))),o}cached(e,t,n){let o=_6(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=_6(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){lv(t,this.bits),uv.set(e,t),k6.delete(e)}hasCache(e){return _6(e)!==1}};function dv(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>gc||n>gc;)t&Vi&&(s=s.add(o)),n&Vi&&(i=i.add(o)),o=o.double(),t>>=Vi,n>>=Vi;return{p1:s,p2:i}}function cv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return A6(e),e}else return mc(r,{isLE:t})}function Y1(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>gc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=cv(e.p,t.Fp,n),s=cv(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function wc(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Es=BigInt(0),Dt=BigInt(1),P6=BigInt(2),gM=BigInt(8);function yM(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function fv(r,e={}){let t=e,n=Y1("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ur(t,{},{uvRatio:"function"});let c=P6<<BigInt(s.BYTES*8)-Dt,l=y=>o.create(y),u=t.uvRatio===void 0?(y,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,g))}}catch{return{isValid:!1,value:Es}}}:t.uvRatio;if(!yM(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(y,g,m=!1){let w=m?Dt:Es;return To("coordinate "+y,g,w,c),g}function f(y){if(!(y instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,Dt,l(i.Gx*i.Gy));static ZERO=new h(Es,Dt,Dt,Es);static Fp=o;static Fn=s;X;Y;Z;T;constructor(g,m,w,x){this.X=d("x",g),this.Y=d("y",m),this.Z=d("z",w,!0),this.T=d("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{x:m,y:w}=g||{};return d("x",m),d("y",w),new h(m,w,Dt,l(m*w))}static fromBytes(g,m=!1){let w=o.BYTES,{a:x,d:E}=i;g=xs(ye(g,w,"point")),Sn(m,"zip215");let S=xs(g),T=g[w-1];S[w-1]=T&-129;let I=Mr(S),C=m?c:o.ORDER;To("point.y",I,Es,C);let U=l(I*I),j=l(U-Dt),z=l(E*U-x),{isValid:v,value:D}=u(j,z);if(!v)throw new Error("bad point: invalid y coordinate");let L=(D&Dt)===Dt,_=(T&128)!==0;if(!m&&D===Es&&_)throw new Error("bad point: x=0 and x_0=1");return _!==L&&(D=l(-D)),h.fromAffine({x:D,y:I})}static fromHex(g,m=!1){return h.fromBytes(hc(g),m)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return p.createCache(this,g),m||this.multiply(P6),this}assertValidity(){let g=this,{a:m,d:w}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:x,Y:E,Z:S,T}=g,I=l(x*x),C=l(E*E),U=l(S*S),j=l(U*U),z=l(I*m),v=l(U*l(z+C)),D=l(j+l(w*l(I*C)));if(v!==D)throw new Error("bad point: equation left != right (1)");let L=l(x*E),_=l(S*T);if(L!==_)throw new Error("bad point: equation left != right (2)")}equals(g){f(g);let{X:m,Y:w,Z:x}=this,{X:E,Y:S,Z:T}=g,I=l(m*T),C=l(E*x),U=l(w*T),j=l(S*x);return I===C&&U===j}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:g}=i,{X:m,Y:w,Z:x}=this,E=l(m*m),S=l(w*w),T=l(P6*l(x*x)),I=l(g*E),C=m+w,U=l(l(C*C)-E-S),j=I+S,z=j-T,v=I-S,D=l(U*z),L=l(j*v),_=l(U*v),k=l(z*j);return new h(D,L,k,_)}add(g){f(g);let{a:m,d:w}=i,{X:x,Y:E,Z:S,T}=this,{X:I,Y:C,Z:U,T:j}=g,z=l(x*I),v=l(E*C),D=l(T*w*j),L=l(S*U),_=l((x+E)*(I+C)-z-v),k=L-D,N=L+D,F=l(v-m*z),P=l(_*k),$=l(N*F),H=l(_*F),Z=l(k*N);return new h(P,$,Z,H)}subtract(g){return f(g),this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:m,f:w}=p.cached(this,g,x=>Hi(h,x));return Hi(h,[m,w])[0]}multiplyUnsafe(g){if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Es?h.ZERO:this.is0()||g===Dt?this:p.unsafe(this,g,m=>Hi(h,m))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(g){let m=this,w=g,{X:x,Y:E,Z:S}=m,T=m.is0();w==null&&(w=T?gM:o.inv(S));let I=l(x*w),C=l(E*w),U=o.mul(S,w);if(T)return{x:Es,y:Dt};if(U!==Dt)throw new Error("invZ was invalid");return{x:I,y:C}}clearCofactor(){return a===Dt?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:m}=this.toAffine(),w=o.toBytes(m);return w[w.length-1]|=g&Dt?128:0,w}toHex(){return fc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new yc(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var X1=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){v6()}static fromHex(e){v6()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return fc(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function hv(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Ur(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(An(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?Fi:o.randomBytes,f=o.adjustScalarBytes===void 0?v=>v:o.adjustScalarBytes,h=o.domain===void 0?(v,D,L)=>{if(Sn(L,"phflag"),D.length||L)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function p(v){return c.create(Mr(v))}function y(v){let D=I.secretKey;ye(v,I.secretKey,"secretKey");let L=ye(n(v),2*D,"hashedSecretKey"),_=f(L.slice(0,D)),k=L.slice(D,2*D),N=p(_);return{head:_,prefix:k,scalar:N}}function g(v){let{head:D,prefix:L,scalar:_}=y(v),k=i.multiply(_),N=k.toBytes();return{head:D,prefix:L,scalar:_,point:k,pointBytes:N}}function m(v){return g(v).pointBytes}function w(v=Uint8Array.of(),...D){let L=xt(...D);return p(n(h(L,ye(v,void 0,"context"),!!s)))}function x(v,D,L={}){v=ye(v,void 0,"message"),s&&(v=s(v));let{prefix:_,scalar:k,pointBytes:N}=g(D),F=w(L.context,_,v),P=i.multiply(F).toBytes(),$=w(L.context,P,N,v),H=c.create(F+$*k);if(!c.isValid(H))throw new Error("sign failed: invalid s");let Z=xt(P,c.toBytes(H));return ye(Z,I.signature,"result")}let E={zip215:o.zip215};function S(v,D,L,_=E){let{context:k}=_,N=_.zip215===void 0?!!E.zip215:_.zip215,F=I.signature;v=ye(v,F,"signature"),D=ye(D,void 0,"message"),L=ye(L,I.publicKey,"publicKey"),N!==void 0&&Sn(N,"zip215"),s&&(D=s(D));let P=F/2,$=v.subarray(0,P),H=Mr(v.subarray(P,F)),Z,fe,ue;try{Z=r.fromBytes(L,N),fe=r.fromBytes($,N),ue=i.multiplyUnsafe(H)}catch{return!1}if(!N&&Z.isSmallOrder())return!1;let Ne=w(k,$,L,D);return fe.add(Z.multiplyUnsafe(Ne)).subtract(ue).clearCofactor().is0()}let T=a.BYTES,I={secretKey:T,publicKey:T,signature:2*T,seed:T};function C(v){return v=v===void 0?d(I.seed):v,ye(v,I.seed,"seed")}function U(v){return Ui(v)&&v.length===I.secretKey}function j(v,D){try{return!!r.fromBytes(v,D===void 0?E.zip215:D)}catch{return!1}}let z={getExtendedPublicKey:g,randomSecretKey:C,isValidSecretKey:U,isValidPublicKey:j,toMontgomery(v){let{y:D}=r.fromBytes(v),L=I.publicKey,_=L===32;if(!_&&L!==57)throw new Error("only defined for 25519 and 448");let k=_?a.div(Dt+D,Dt-D):a.div(D-Dt,D+Dt);return a.toBytes(k)},toMontgomerySecret(v){let D=I.secretKey;ye(v,D);let L=n(v.subarray(0,D));return f(L).subarray(0,D)}};return Object.freeze(I),Object.freeze(z),Object.freeze({keygen:wc(C,m),getPublicKey:m,sign:x,verify:S,utils:z,Point:r,lengths:I})}function ju(r,e){if(An(r),An(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function wM(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function bM(r){if(!Ui(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?G1(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function L6(r,e,t,n){ye(r),An(t),e=bM(e),e.length>255&&(e=n(xt(G1("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=xt(e,ju(e.length,1)),c=new Uint8Array(s),l=ju(t,2),u=new Array(i),d=n(xt(c,r,l,ju(0,1),a));u[0]=n(xt(d,ju(1,1),a));for(let h=1;h<i;h++){let p=[wM(d,u[h-1]),ju(h+1,1),a];u[h]=n(xt(...p))}return xt(...u).slice(0,t)}var pv="HashToScalar-";var Yu=BigInt(0),bc=BigInt(1),Q1=BigInt(2);function xM(r){return Ur(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function mv(r){let e=xM(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?Fi:i,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),h=a?Q1**BigInt(254):Q1**BigInt(447),p=a?BigInt(8)*Q1**BigInt(251)-bc:BigInt(4)*Q1**BigInt(445)-bc,y=h+p+bc,g=L=>tt(L,t),m=w(d);function w(L){return qu(g(L),u)}function x(L){let _=xs(ye(L,u,"uCoordinate"));return a&&(_[31]&=127),g(Mr(_))}function E(L){return Mr(o(xs(ye(L,u,"scalar"))))}function S(L,_){let k=j(x(_),E(L));if(k===Yu)throw new Error("invalid private or public key received");return w(k)}function T(L){return S(L,m)}let I=T,C=S;function U(L,_,k){let N=g(L*(_-k));return _=g(_-N),k=g(k+N),{x_2:_,x_3:k}}function j(L,_){To("u",L,Yu,t),To("scalar",_,h,y);let k=_,N=L,F=bc,P=Yu,$=L,H=bc,Z=Yu;for(let ue=BigInt(l-1);ue>=Yu;ue--){let Ne=k>>ue&bc;Z^=Ne,{x_2:F,x_3:$}=U(Z,F,$),{x_2:P,x_3:H}=U(Z,P,H),Z=Ne;let Oe=F+P,Be=g(Oe*Oe),Ie=F-P,Je=g(Ie*Ie),uo=Be-Je,ei=$+H,wa=$-H,Ul=g(wa*Oe),Fl=g(ei*Ie),hb=Ul+Fl,pb=Ul-Fl;$=g(hb*hb),H=g(N*g(pb*pb)),F=g(Be*Je),P=g(uo*(Be+g(f*uo)))}({x_2:F,x_3:$}=U(Z,F,$)),{x_2:P,x_3:H}=U(Z,P,H);let fe=s(P);return g(F*fe)}let z={secretKey:u,publicKey:u,seed:u},v=L=>(L=L===void 0?c(u):L,ye(L,z.seed,"seed"),L),D={randomSecretKey:v};return Object.freeze(z),Object.freeze(D),Object.freeze({keygen:wc(v,I),getSharedSecret:C,getPublicKey:I,scalarMult:S,scalarMultBase:T,utils:D,GuBytes:m.slice(),lengths:z})}var EM=BigInt(0),ko=BigInt(1),gv=BigInt(2),vM=BigInt(3),SM=BigInt(5),AM=BigInt(8),qi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),O6={p:qi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:AM,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function bv(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=qi,a=r*r%s*r%s,c=Ye(a,gv,s)*a%s,l=Ye(c,ko,s)*r%s,u=Ye(l,SM,s)*l%s,d=Ye(u,e,s)*u%s,f=Ye(d,t,s)*d%s,h=Ye(f,n,s)*f%s,p=Ye(h,o,s)*h%s,y=Ye(p,o,s)*h%s,g=Ye(y,e,s)*u%s;return{pow_p_5_8:Ye(g,gv,s)*r%s,b2:a}}function xv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var D6=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function B6(r,e){let t=qi,n=tt(e*e*e,t),o=tt(n*n*e,t),s=bv(r*o).pow_p_5_8,i=tt(r*n*s,t),a=tt(e*i*i,t),c=i,l=tt(i*D6,t),u=a===r,d=a===tt(-r,t),f=a===tt(-r*D6,t);return u&&(i=c),(d||f)&&(i=l),Co(i,t)&&(i=tt(-i,t)),{isValid:u||d,value:i}}var Ss=fv(O6,{uvRatio:B6}),vs=Ss.Fp,Ev=Ss.Fn;function IM(r){return hv(Ss,Hn,Object.assign({adjustScalarBytes:xv,zip215:!0},r))}var Xu=IM({});var Qu=(()=>{let r=qi;return mv({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=bv(e);return tt(Ye(t,vM,r)*n,r)},adjustScalarBytes:xv})})();var R6=D6,TM=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),CM=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kM=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),_M=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),yv=r=>B6(ko,r),PM=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),N6=r=>vs.create(Mr(r)&PM);function wv(r){let{d:e}=O6,t=qi,n=m=>vs.create(m),o=n(R6*r*r),s=n((o+ko)*kM),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=B6(s,a),u=n(l*r);Co(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let d=n(i*(o-ko)*_M-a),f=l*l,h=n((l+l)*a),p=n(d*TM),y=n(ko-f),g=n(ko+f);return new Ss(n(h*g),n(y*p),n(p*g),n(h*y))}var As=class r extends X1{static BASE=new r(Ss.BASE);static ZERO=new r(Ss.ZERO);static Fp=vs;static Fn=Ev;constructor(e){super(e)}static fromAffine(e){return new r(Ss.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ut(e,32);let{a:t,d:n}=O6,o=qi,s=E=>vs.create(E),i=N6(e);if(!GE(vs.toBytes(i),e)||Co(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ko+t*a),l=s(ko-t*a),u=s(c*c),d=s(l*l),f=s(t*n*u-d),{isValid:h,value:p}=yv(s(f*d)),y=s(p*l),g=s(p*y*f),m=s((i+i)*y);Co(m,o)&&(m=s(-m));let w=s(c*g),x=s(m*w);if(!h||Co(x,o)||w===EM)throw new Error("invalid ristretto255 encoding 2");return new r(new Ss(m,w,ko,x))}static fromHex(e){return r.fromBytes(Fu(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=qi,i=g=>vs.create(g),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=yv(i(a*l)),d=i(u*a),f=i(u*c),h=i(d*f*o),p;if(Co(o*h,s)){let g=i(t*R6),m=i(e*R6);e=g,t=m,p=i(d*CM)}else p=f;Co(e*h,s)&&(t=i(-t));let y=i((n-t)*p);return Co(y,s)&&(y=i(-y)),vs.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>vs.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(As.BASE);Object.freeze(As.ZERO);Object.freeze(As.prototype);Object.freeze(As);var LM=Object.freeze({Point:As,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=L6(r,t,64,Hn);return LM.deriveToCurve(n)},hashToScalar(r,e={DST:pv}){let t=L6(r,e.DST,64,Hn);return Ev.create(Mr(t))},deriveToCurve(r){Ut(r,64);let e=N6(r.subarray(0,32)),t=wv(e),n=N6(r.subarray(32,64)),o=wv(n);return new As(t.add(o))}});var Ju=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Zu=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},J1=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var yt={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new J1("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 zi=32,Fr=64,M6=32;var xc,vv=(async()=>{try{return await yt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Sv(){let r=Xu.utils.randomSecretKey(),e=Xu.getPublicKey(r);return{privateKey:BM(r,e),publicKey:e}}async function DM(r,e){let t;r.length===Fr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:M(r.subarray(32),"base64url"),d:M(t,"base64url"),ext:!0,key_ops:["sign"]},o=await yt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await yt.get().subtle.sign({name:"Ed25519"},o,ee(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function RM(r,e){let t=r.subarray(0,M6);return Xu.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Av(r,e){return xc==null&&(xc=await vv),xc?DM(r,e):RM(r,e)}async function NM(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await yt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await yt.get().subtle.verify({name:"Ed25519"},n,ee(e),ee(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function OM(r,e,t){return Xu.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Iv(r,e,t){return xc==null&&(xc=await vv),xc?NM(r,e,t):OM(r,e,t)}function BM(r,e){let t=new Uint8Array(Fr);for(let n=0;n<M6;n++)t[n]=r[n],t[M6+n]=e[n];return t}function Ec(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ed=class{type="Ed25519";raw;constructor(e){this.raw=Sc(e,zi)}toMultihash(){return Ze.digest(Lt(this))}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Iv(this.raw,t,e);return Ec(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},vc=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Sc(e,Fr),this.publicKey=new ed(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Av(this.raw,e);return Ec(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function U6(r){if(r.length>Fr){r=Sc(r,Fr+zi);let n=r.subarray(0,Fr),o=r.subarray(Fr,r.length);return new vc(n,o)}r=Sc(r,Fr);let e=r.subarray(0,Fr),t=r.subarray(zi);return new vc(e,t)}function F6(r){return r=Sc(r,zi),new ed(r)}async function Cv(){let{privateKey:r,publicKey:e}=Sv();return new vc(r,e)}function Sc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new A(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Fe||(Fe={}));var $6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})($6||($6={}));(function(r){r.codec=()=>et($6)})(Fe||(Fe={}));var qn;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Fe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(qn||(qn={}));var td;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Fe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(td||(td={}));var nd={};V(nd,{MAX_RSA_KEY_SIZE:()=>K6,generateRSAKeyPair:()=>X6,jwkToJWKKeyPair:()=>Lv,jwkToPkcs1:()=>$M,jwkToPkix:()=>z6,jwkToRSAPrivateKey:()=>Y6,pkcs1MessageToJwk:()=>H6,pkcs1MessageToRSAPrivateKey:()=>Z1,pkcs1ToJwk:()=>FM,pkcs1ToRSAPrivateKey:()=>W6,pkixMessageToJwk:()=>q6,pkixMessageToRSAPublicKey:()=>j6,pkixToJwk:()=>KM,pkixToRSAPublicKey:()=>G6});var Ac=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=nd.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return K.createV1(114,this._multihash)}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return Pv(this.jwk,t,e,n)}},rd=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=nd.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return _v(this.jwk,e,t)}};var K6=8192,V6=18,MM=1062,UM=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function FM(r){let e=Jr(r);return H6(e)}function H6(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function $M(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 A("JWK was missing components");return En([ur(Uint8Array.from([0])),ur(O(r.n,"base64url")),ur(O(r.e,"base64url")),ur(O(r.d,"base64url")),ur(O(r.p,"base64url")),ur(O(r.q,"base64url")),ur(O(r.dp,"base64url")),ur(O(r.dq,"base64url")),ur(O(r.qi,"base64url"))]).subarray()}function KM(r){let e=Jr(r,{offset:0});return q6(e)}function q6(r){let e=Jr(r[1],{offset:0});return{kty:"RSA",n:M(e[0],"base64url"),e:M(e[1],"base64url")}}function z6(r){if(r.n==null||r.e==null)throw new A("JWK was missing components");return En([UM,Uu(En([ur(O(r.n,"base64url")),ur(O(r.e,"base64url"))]))]).subarray()}function W6(r){let e=Jr(r);return Z1(e)}function Z1(r){let e=H6(r);return Y6(e)}function G6(r,e){if(r.byteLength>=MM)throw new fo("Key size is too large");let t=Jr(r,{offset:0});return j6(t,r,e)}function j6(r,e,t){let n=q6(r);if(t==null){let o=Zr(qn.encode({Type:Fe.RSA,Data:e}));t=sr(V6,o)}return new Ac(n,t)}function Y6(r){if(Rv(r)>K6)throw new A("Key size is too large");let e=Lv(r),t=Zr(qn.encode({Type:Fe.RSA,Data:z6(e.publicKey)})),n=sr(V6,t);return new rd(e.privateKey,new Ac(e.publicKey,n))}async function X6(r){if(r>K6)throw new A("Key size is too large");let e=await Dv(r),t=Zr(qn.encode({Type:Fe.RSA,Data:z6(e.publicKey)})),n=sr(V6,t);return new rd(e.privateKey,new Ac(e.publicKey,n))}function Lv(r){if(r==null)throw new A("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Dv(r,e){let t=await yt.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 VM(t,e);return{privateKey:n[0],publicKey:n[1]}}async function _v(r,e,t){let n=await yt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await yt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,ee(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Pv(r,e,t,n){let o=await yt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await yt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,ee(e),ee(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function VM(r,e){if(r.privateKey==null||r.publicKey==null)throw new A("Private and public key are required");let t=await Promise.all([yt.get().subtle.exportKey("jwk",r.privateKey),yt.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Rv(r){if(r.kty!=="RSA")throw new A("invalid key type");if(r.n==null)throw new A("invalid key modulus");return O(r.n,"base64url").length*8}var ep=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ao(e),Ut(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Qt(o)}update(e){return dc(this),this.iHash.update(e),this}digestInto(e){dc(this),M1(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Wi=(()=>{let r=((e,t,n)=>new ep(e,t).update(n).digest());return r.create=(e,t)=>new ep(e,t),r})();var Nv=(r,e)=>(r+(r>=0?e:-e)/Ov)/e;function HM(r,e,t){To("scalar",r,zn,t);let[[n,o],[s,i]]=e,a=Nv(i*r,t),c=Nv(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,d=l<zn,f=u<zn;d&&(l=-l),f&&(u=-u);let h=zu(Math.ceil(pc(t)/2))+Is;if(l<zn||l>=h||u<zn||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function J6(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Q6(r,e){Ur(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Sn(t.lowS,"lowS"),Sn(t.prehash,"prehash"),t.format!==void 0&&J6(t.format),t}var Z6=class extends Error{constructor(e=""){super(e)}},In={Err:Z6,_tlv:{encode:(r,e)=>{let{Err:t}=In;if(An(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Hu(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Hu(o.length/2|128):"";return Hu(r)+s+o+e},decode(r,e){let{Err:t}=In;e=ye(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)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}=In;if(z1(r),r<zn)throw new e("integer: negative integers are not allowed");let t=Hu(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}=In;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 $i(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=In,o=ye(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=In,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(In._tlv);Object.freeze(In._int);Object.freeze(In);var zn=BigInt(0),Is=BigInt(1),Ov=BigInt(2),tp=BigInt(3),qM=BigInt(4);function Bv(r,e={}){let t=Y1("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Ur(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Uv(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(z,v,D){if(l&&v.is0())return Uint8Array.of(0);let{x:L,y:_}=v.toAffine(),k=n.toBytes(L);if(Sn(D,"isCompressed"),D){d();let N=!n.isOdd(_);return xt(Mv(N),k)}else return xt(Uint8Array.of(4),k,n.toBytes(_))}function h(z){ye(z,void 0,"Point");let{publicKey:v,publicKeyUncompressed:D}=u,L=z.length,_=z[0],k=z.subarray(1);if(l&&L===1&&_===0)return{x:n.ZERO,y:n.ZERO};if(L===v&&(_===2||_===3)){let N=n.fromBytes(k);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let F=g(N),P;try{P=n.sqrt(F)}catch(Z){let fe=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+fe)}d();let $=n.isOdd(P);return(_&1)===1!==$&&(P=n.neg(P)),{x:N,y:P}}else if(L===D&&_===4){let N=n.BYTES,F=n.fromBytes(k.subarray(0,N)),P=n.fromBytes(k.subarray(N,N*2));if(!m(F,P))throw new Error("bad point: is not on curve");return{x:F,y:P}}else throw new Error(`bad point: got length ${L}, expected compressed=${v} or uncompressed=${D}`)}let p=e.toBytes===void 0?f:e.toBytes,y=e.fromBytes===void 0?h:e.fromBytes;function g(z){let v=n.sqr(z),D=n.mul(v,z);return n.add(n.add(D,n.mul(z,s.a)),s.b)}function m(z,v){let D=n.sqr(v),L=g(z);return n.eql(D,L)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,tp),qM),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,x)))throw new Error("bad curve params: a or b");function E(z,v,D=!1){if(!n.isValid(v)||D&&n.is0(v))throw new Error(`bad point coordinate ${z}`);return v}function S(z){if(!(z instanceof C))throw new Error("Weierstrass Point expected")}function T(z){if(!c||!c.basises)throw new Error("no endo");return HM(z,c.basises,o.ORDER)}function I(z,v,D,L,_){return D=new C(n.mul(D.X,z),D.Y,D.Z),v=Gu(L,v),D=Gu(_,D),v.add(D)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(v,D,L){this.X=E("x",v),this.Y=E("y",D,!0),this.Z=E("z",L),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){let{x:D,y:L}=v||{};if(!v||!n.isValid(D)||!n.isValid(L))throw new Error("invalid affine point");if(v instanceof C)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(L)?C.ZERO:new C(D,L,n.ONE)}static fromBytes(v){let D=C.fromAffine(y(ye(v,void 0,"point")));return D.assertValidity(),D}static fromHex(v){return C.fromBytes(hc(v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,D=!0){return j.createCache(this,v),D||this.multiply(tp),this}assertValidity(){let v=this;if(v.is0()){if(e.allowInfinityPoint&&n.is0(v.X)&&n.eql(v.Y,n.ONE)&&n.is0(v.Z))return;throw new Error("bad point: ZERO")}let{x:D,y:L}=v.toAffine();if(!n.isValid(D)||!n.isValid(L))throw new Error("bad point: x or y not field elements");if(!m(D,L))throw new Error("bad point: equation left != right");if(!v.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:v}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(v)}equals(v){S(v);let{X:D,Y:L,Z:_}=this,{X:k,Y:N,Z:F}=v,P=n.eql(n.mul(D,F),n.mul(k,_)),$=n.eql(n.mul(L,F),n.mul(N,_));return P&&$}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:v,b:D}=s,L=n.mul(D,tp),{X:_,Y:k,Z:N}=this,F=n.ZERO,P=n.ZERO,$=n.ZERO,H=n.mul(_,_),Z=n.mul(k,k),fe=n.mul(N,N),ue=n.mul(_,k);return ue=n.add(ue,ue),$=n.mul(_,N),$=n.add($,$),F=n.mul(v,$),P=n.mul(L,fe),P=n.add(F,P),F=n.sub(Z,P),P=n.add(Z,P),P=n.mul(F,P),F=n.mul(ue,F),$=n.mul(L,$),fe=n.mul(v,fe),ue=n.sub(H,fe),ue=n.mul(v,ue),ue=n.add(ue,$),$=n.add(H,H),H=n.add($,H),H=n.add(H,fe),H=n.mul(H,ue),P=n.add(P,H),fe=n.mul(k,N),fe=n.add(fe,fe),H=n.mul(fe,ue),F=n.sub(F,H),$=n.mul(fe,Z),$=n.add($,$),$=n.add($,$),new C(F,P,$)}add(v){S(v);let{X:D,Y:L,Z:_}=this,{X:k,Y:N,Z:F}=v,P=n.ZERO,$=n.ZERO,H=n.ZERO,Z=s.a,fe=n.mul(s.b,tp),ue=n.mul(D,k),Ne=n.mul(L,N),Oe=n.mul(_,F),Be=n.add(D,L),Ie=n.add(k,N);Be=n.mul(Be,Ie),Ie=n.add(ue,Ne),Be=n.sub(Be,Ie),Ie=n.add(D,_);let Je=n.add(k,F);return Ie=n.mul(Ie,Je),Je=n.add(ue,Oe),Ie=n.sub(Ie,Je),Je=n.add(L,_),P=n.add(N,F),Je=n.mul(Je,P),P=n.add(Ne,Oe),Je=n.sub(Je,P),H=n.mul(Z,Ie),P=n.mul(fe,Oe),H=n.add(P,H),P=n.sub(Ne,H),H=n.add(Ne,H),$=n.mul(P,H),Ne=n.add(ue,ue),Ne=n.add(Ne,ue),Oe=n.mul(Z,Oe),Ie=n.mul(fe,Ie),Ne=n.add(Ne,Oe),Oe=n.sub(ue,Oe),Oe=n.mul(Z,Oe),Ie=n.add(Ie,Oe),ue=n.mul(Ne,Ie),$=n.add($,ue),ue=n.mul(Je,Ie),P=n.mul(Be,P),P=n.sub(P,ue),ue=n.mul(Be,Ne),H=n.mul(Je,H),H=n.add(H,ue),new C(P,$,H)}subtract(v){return S(v),this.add(v.negate())}is0(){return this.equals(C.ZERO)}multiply(v){let{endo:D}=e;if(!o.isValidNot0(v))throw new RangeError("invalid scalar: out of range");let L,_,k=N=>j.cached(this,N,F=>Hi(C,F));if(D){let{k1neg:N,k1:F,k2neg:P,k2:$}=T(v),{p:H,f:Z}=k(F),{p:fe,f:ue}=k($);_=Z.add(ue),L=I(D.beta,H,fe,N,P)}else{let{p:N,f:F}=k(v);L=N,_=F}return Hi(C,[L,_])[0]}multiplyUnsafe(v){let{endo:D}=e,L=this,_=v;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===zn||L.is0())return C.ZERO;if(_===Is)return L;if(j.hasCache(this))return this.multiply(_);if(D){let{k1neg:k,k1:N,k2neg:F,k2:P}=T(_),{p1:$,p2:H}=dv(C,L,N,P);return I(D.beta,$,H,k,F)}else return j.unsafe(L,_)}toAffine(v){let D=this,L=v,{X:_,Y:k,Z:N}=D;if(n.eql(N,n.ONE))return{x:_,y:k};let F=D.is0();L==null&&(L=F?n.ONE:n.inv(N));let P=n.mul(_,L),$=n.mul(k,L),H=n.mul(N,L);if(F)return{x:n.ZERO,y:n.ZERO};if(!n.eql(H,n.ONE))throw new Error("invZ was invalid");return{x:P,y:$}}isTorsionFree(){let{isTorsionFree:v}=e;return i===Is?!0:v?v(C,this):j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return i===Is?this:v?v(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Is?this.is0():this.clearCofactor().is0()}toBytes(v=!0){return Sn(v,"isCompressed"),this.assertValidity(),p(C,this,v)}toHex(v=!0){return fc(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=o.BITS,j=new yc(C,e.endo?Math.ceil(U/2):U);return U>=8&&C.BASE.precompute(8),Object.freeze(C.prototype),Object.freeze(C),C}function Mv(r){return Uint8Array.of(r?2:3)}function Uv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function zM(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Fi:e.randomBytes,o=Object.assign(Uv(r.Fp,t),{seed:Math.max(I6(t.ORDER),16)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:y,publicKeyUncompressed:g}=o;try{let m=h.length;return p===!0&&m!==y||p===!1&&m!==g?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,T6(ye(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:g}=o,m=t._lengths;if(!Ui(h))return;let w=ye(h,void 0,"key").length,x=w===y||w===g,E=w===p||!!m?.includes(w);if(!(x&&E))return x}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h);return r.fromBytes(p).multiply(g).toBytes(y)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},f=wc(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:o})}function Fv(r,e,t={}){let n=e;Ao(n),Ur(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Fi:t.randomBytes,s=t.hmac===void 0?(_,k)=>Wi(n,_,k):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=zM(r,t),y={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=c*Ov+Is<i.ORDER;function m(_){let k=c>>Is;return _>k}function w(_,k){if(!a.isValidNot0(k))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return k}function x(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(_,k){J6(k);let N=p.signature,F=k==="compact"?N:k==="recovered"?N+1:void 0;return ye(_,F)}class S{r;s;recovery;constructor(k,N,F){if(this.r=w("r",k),this.s=w("s",N),F!=null){if(x(),![0,1,2,3].includes(F))throw new Error("invalid recovery id");this.recovery=F}Object.freeze(this)}static fromBytes(k,N=y.format){E(k,N);let F;if(N==="der"){let{r:Z,s:fe}=In.toSig(ye(k));return new S(Z,fe)}N==="recovered"&&(F=k[0],N="compact",k=k.subarray(1));let P=p.signature/2,$=k.subarray(0,P),H=k.subarray(P,P*2);return new S(a.fromBytes($),a.fromBytes(H),F)}static fromHex(k,N){return this.fromBytes(hc(k),N)}assertRecovery(){let{recovery:k}=this;if(k==null)throw new Error("invalid recovery id: must be present");return k}addRecoveryBit(k){return new S(this.r,this.s,k)}recoverPublicKey(k){let{r:N,s:F}=this,P=this.assertRecovery(),$=P===2||P===3?N+c:N;if(!i.isValid($))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes($),Z=r.fromBytes(xt(Mv((P&1)===0),H)),fe=a.inv($),ue=I(ye(k,void 0,"msgHash")),Ne=a.create(-ue*fe),Oe=a.create(F*fe),Be=r.BASE.multiplyUnsafe(Ne).add(Z.multiplyUnsafe(Oe));if(Be.is0())throw new Error("invalid recovery: point at infinify");return Be.assertValidity(),Be}hasHighS(){return m(this.s)}toBytes(k=y.format){if(J6(k),k==="der")return hc(In.hexFromSig(this));let{r:N,s:F}=this,P=a.toBytes(N),$=a.toBytes(F);return k==="recovered"?(x(),xt(Uint8Array.of(this.assertRecovery()),P,$)):xt(P,$)}toHex(k){return fc(this.toBytes(k))}}Object.freeze(S.prototype),Object.freeze(S);let T=t.bits2int===void 0?function(k){if(k.length>8192)throw new Error("input is too large");let N=$i(k),F=k.length*8-l;return F>0?N>>BigInt(F):N}:t.bits2int,I=t.bits2int_modN===void 0?function(k){return a.create(T(k))}:t.bits2int_modN,C=zu(l);function U(_){return To("num < 2^"+l,_,zn,C),a.toBytes(_)}function j(_,k){return ye(_,void 0,"message"),k?ye(n(_),void 0,"prehashed message"):_}function z(_,k,N){let{lowS:F,prehash:P,extraEntropy:$}=Q6(N,y);_=j(_,P);let H=I(_),Z=a.fromBytes(k);if(!a.isValidNot0(Z))throw new Error("invalid private key");let fe=[U(Z),U(H)];if($!=null&&$!==!1){let Be=$===!0?o(p.secretKey):$;fe.push(ye(Be,void 0,"extraEntropy"))}let ue=xt(...fe),Ne=H;function Oe(Be){let Ie=T(Be);if(!a.isValidNot0(Ie))return;let Je=a.inv(Ie),uo=r.BASE.multiply(Ie).toAffine(),ei=a.create(uo.x);if(ei===zn)return;let wa=a.create(Je*a.create(Ne+ei*Z));if(wa===zn)return;let Ul=(uo.x===ei?0:2)|Number(uo.y&Is),Fl=wa;return F&&m(wa)&&(Fl=a.neg(wa),Ul^=1),new S(ei,Fl,g?void 0:Ul)}return{seed:ue,k2sig:Oe}}function v(_,k,N={}){let{seed:F,k2sig:P}=z(_,k,N);return jE(n.outputLen,a.BYTES,s)(F,P).toBytes(N.format)}function D(_,k,N,F={}){let{lowS:P,prehash:$,format:H}=Q6(F,y);if(N=ye(N,void 0,"publicKey"),k=j(k,$),!Ui(_)){let Z=_ instanceof S?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Z)}E(_,H);try{let Z=S.fromBytes(_,H),fe=r.fromBytes(N);if(P&&Z.hasHighS())return!1;let{r:ue,s:Ne}=Z,Oe=I(k),Be=a.inv(Ne),Ie=a.create(Oe*Be),Je=a.create(ue*Be),uo=r.BASE.multiplyUnsafe(Ie).add(fe.multiplyUnsafe(Je));return uo.is0()?!1:a.create(uo.x)===ue}catch{return!1}}function L(_,k,N={}){let{prehash:F}=Q6(N,y);return k=j(k,F),S.fromBytes(_,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:v,verify:D,recoverPublicKey:L,Signature:S,hash:n})}var ty={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},WM={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var $v=BigInt(2);function GM(r){let e=ty.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Ye(u,t,e)*u%e,f=Ye(d,t,e)*u%e,h=Ye(f,$v,e)*l%e,p=Ye(h,o,e)*h%e,y=Ye(p,s,e)*p%e,g=Ye(y,a,e)*y%e,m=Ye(g,c,e)*g%e,w=Ye(m,a,e)*y%e,x=Ye(w,t,e)*u%e,E=Ye(x,i,e)*p%e,S=Ye(E,n,e)*l%e,T=Ye(S,$v,e);if(!ey.eql(ey.sqr(T),r))throw new Error("Cannot find square root");return T}var ey=mc(ty.p,{sqrt:GM}),jM=Bv(ty,{Fp:ey,endo:WM}),Tn=Fv(jM,Zr);var Kv=32;function Vv(r,e,t){let n=He.digest(e instanceof Uint8Array?e:e.subarray());if(Ec(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Tn.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Ju(String(o))});try{return Tn.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Ju(String(o))}}function Hv(r,e,t,n){let o=He.digest(t instanceof Uint8Array?t:t.subarray());if(Ec(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Tn.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Zu(String(s))});try{return n?.signal?.throwIfAborted(),Tn.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Zu(String(s))}}var od=class{type="secp256k1";raw;_key;constructor(e){this._key=Wv(e),this.raw=qv(this._key)}toMultihash(){return Ze.digest(Lt(this))}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return Hv(this._key,t,e,n)}},sd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=zv(e),this.publicKey=new od(t??Gv(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return Vv(this.raw,e,t)}};function ry(r){return new sd(r)}function ny(r){return new od(r)}async function jv(){let r=YM();return new sd(r)}function qv(r){return Tn.Point.fromBytes(r).toBytes()}function zv(r){try{return Tn.getPublicKey(r,!0),r}catch(e){throw new $l(String(e))}}function Wv(r){try{return Tn.Point.fromBytes(r),r}catch(e){throw new fo(String(e))}}function Gv(r){try{return Tn.getPublicKey(r,!0)}catch(e){throw new $l(String(e))}}function YM(){return Tn.utils.randomSecretKey()}async function rp(r,e){if(r==="Ed25519")return Cv();if(r==="secp256k1")return jv();if(r==="RSA")return X6(XM(e));if(r==="ECDSA")return LE(QM(e));throw new cn}function Et(r,e){let{Type:t,Data:n}=qn.decode(r),o=n??new Uint8Array;switch(t){case Fe.RSA:return G6(o,e);case Fe.Ed25519:return F6(o);case Fe.secp256k1:return ny(o);case Fe.ECDSA:return l6(o);default:throw new cn}}function Yv(r){let{Type:e,Data:t}=qn.decode(r.digest),n=t??new Uint8Array;switch(e){case Fe.Ed25519:return F6(n);case Fe.secp256k1:return ny(n);case Fe.ECDSA:return l6(n);default:throw new cn}}function Lt(r){return qn.encode({Type:Fe[r.type],Data:r.raw})}function Xv(r){let e=td.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Fe.RSA:return W6(t);case Fe.Ed25519:return U6(t);case Fe.secp256k1:return ry(t);case Fe.ECDSA:return TE(t);default:throw new cn}}function Qv(r){if(r.byteLength===Fr)return U6(r);if(r.byteLength===Kv)return ry(r);let e=Jr(r),t=e[2]?.[0];if(t===mE||t===gE||t===yE)return c6(e);if(e.length>8)return Z1(e);throw new A("Could not extract private key from raw bytes")}function Gi(r){return td.encode({Type:Fe[r.type],Data:r.raw})}function XM(r){return r==null?2048:parseInt(r,10)}function QM(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 A("Unsupported curve, should be P-256, P-384 or P-521")}var Jv=Symbol.for("nodejs.util.inspect.custom"),JM=114,id=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()})`}[yh]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return K.createV1(JM,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Jv](){return`PeerId(${this.toString()})`}},ad=class extends id{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},cd=class extends id{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ld=class extends id{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},ZM=2336,ud=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ze.digest(O(this.url))}[Jv](){return`PeerId(${this.url})`}[yh]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return K.createV1(ZM,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=M(e)),e.toString()===this.toString())}};var eU=114,Zv=2336;function Xe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ee(ge.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return vt(K.parse(r));if(e==null)throw new A('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ee(e.decode(r))}return wt(t)}function Wn(r){if(r.type==="Ed25519")return new cd({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ld({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ad({multihash:r.toCID().multihash,publicKey:r});throw new cn}function eS(r){return Wn(r.publicKey)}function wt(r){if(rU(r))return new ad({multihash:r});if(tU(r))try{let e=Yv(r);if(e.type==="Ed25519")return new cd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ld({multihash:r,publicKey:e})}catch{let t=M(r.digest);return new ud(new URL(t))}throw new va("Supplied PeerID Multihash is invalid")}function vt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==eU&&r.code!==Zv)throw new dh("Supplied PeerID CID is invalid");if(r.code===Zv){let e=M(r.multihash.digest);return new ud(new URL(e))}return wt(r.multihash)}function tU(r){return r.code===Ze.code}function rU(r){return r.code===He.code}function nU(r){return r[Symbol.asyncIterator]!=null}function oU(r){if(nU(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Er=oU;function sU(r){return r[Symbol.asyncIterator]!=null}function iU(r,e){let t=0;if(sU(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=ic(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,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 Kt=iU;function aU(r){return r[Symbol.asyncIterator]!=null}function cU(r,e){return aU(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 Ts=cU;var oy="/ipfs/bitswap/1.2.0";var rt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(rt||(rt={}));var sy;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(sy||(sy={}));(function(r){r.codec=()=>et(sy)})(rt||(rt={}));var ji;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),rt.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:me(0),priority:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=rt.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:rt.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(ji||(ji={}));var dd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),ji.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new he('Decode error - repeated field "entries" had too many elements');c.entries.push(ji.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new he('Streaming decode error - repeated field "entries" had too many elements');for(let f of ji.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(dd||(dd={}));var Yi;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:me(0),data:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Yi||(Yi={}));var $r;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})($r||($r={}));var np;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(np||(np={}));(function(r){r.codec=()=>et(np)})($r||($r={}));var Xi;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&np[s.type]!==0&&(i.uint32(16),$r.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:me(0),type:$r.HaveBlock},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=$r.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:$r.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Xi||(Xi={}));var Qi;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),dd.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Yi.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Xi.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=dd.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new he('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Yi.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new he('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Xi.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield*dd.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new he('Streaming decode error - repeated field "blocks" had too many elements');for(let f of Yi.codec().stream(s,s.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 he('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of Xi.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Qi||(Qi={}));function tS(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.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 op=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var lU=4193648,uU=lU+16;function*rS(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Qi.encode(l).byteLength,{added:d,hasMore:f,newSize:h}=iy(o,l.blocks,a,e,u,dU);a+=d,u=h;let p=f;({added:d,hasMore:f,newSize:h}=iy(n,l.blockPresences,i,e,u,fU)),i+=d,u=h;let y=f;if({added:d,hasMore:f,newSize:h}=iy(t,l.wantlist.entries,s,e,u,hU),s+=d,u=h,c=!p&&!y&&!f,c||(l.wantlist.full=!1),yield Qi.encode(l),c)break}}function iy(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=s(l);if(u>uU)throw new op("Cannot send block as after encoding it is over the max message size");let d=o+u;if(d>n){a=!0;break}e.push(l),i++,o=d}return{hasMore:a,added:i,newSize:o}}function dU(r){return ay(3,Yi.encode(r))}function fU(r){return ay(4,Xi.encode(r))}function hU(r){return ay(1,ji.encode(r))}function ay(r,e){let t=we(r),n=we(e.byteLength);return t+n+e.byteLength}function SU(r){if(yr(r))return r;if(ac(r))return vt(r);if(jr(r)||Array.isArray(r))return r;throw new A(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var sp=class extends le{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??[oy],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 Xt({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 Bn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=Mt();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of Pi(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Qi.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}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.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 R("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 R("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Er(Kt(Ts(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 o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=tS(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new A("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new R("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,oy,s);await a.closeRead(s);try{for(let c of rS(i,this.maxOutgoingMessageSize))a.send(Eo.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new R("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 Cr("Network isn't running");return e=SU(e),t?.onProgress?.(new R("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 Ji(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function ip(r){let e=Ee(ge.decode(`z${r}`));return wt(e)}var Jt=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 Ji(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 Ji(this.map.values(),e=>e.key)}values(){return Ji(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Kr=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 Ji(this.set.entries(),e=>{let t=ip(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ip(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ji(this.set.values(),e=>ip(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 cy(){return new Kr}var ap=class{filter;constructor(e,t){this.filter=Nt(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 ly(r,e=.001){return new ap(r,e)}var uy=class extends Jt{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 _o(r){let{name:e,metrics:t}=r,n;return t!=null?n=new uy({name:e,metrics:t}):n=new Jt,n}var Po=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=$e.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=$e.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=$e.encode(e.multihash.bytes);this.blocks.set(n,t)}};function AU(r){let e=new Uint8Array(r.reduce((n,o)=>n+we(o),0)),t=0;for(let n of r)e=Gt(n,e,t),t+=we(n);return e}var nS=AU;function dy(r){return nS([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var cp=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;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}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,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=K.decode(n.cid),s=M(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===rt.WantHave&&(n.wantType==null||n.wantType===rt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??rt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??rt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[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=M(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Po,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await N1(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===rt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:dy(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:$r.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:dy(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:$r.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((s,i)=>s+i.data.byteLength,0)))}};var lp=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;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.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=_o({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}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}}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)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new cp({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var fy=class extends sc{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){let o=vt(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.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,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(ac(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new R("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function oS(r,e){return new fy(r,e)}var up=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 Vr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Hr(r,e,t,n){let o=new Vr(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){py(t,"abort",d),py(r,e,l),py(r,s,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(o)};hy(t,"abort",d),hy(r,e,l),hy(r,s,u)})}function hy(r,e,t){r!=null&&(sS(r)?r.addEventListener(e,t):r.addListener(e,t))}function py(r,e,t){r!=null&&(sS(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function sS(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function IU(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=_r(r);e.push(t),r=r.slice(we(t))}return e}var iS=IU;var dp=class extends le{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=_o({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=gt({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(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=M(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===rt.WantHave&&t.wantType===rt.WantBlock&&(o.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===rt.WantBlock?(await Hr(this,"block",t?.signal,{filter:a=>te(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Hr(this,"presence",t?.signal,{filter:i=>te(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),o.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=qe(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Po;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).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=M(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Po;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Hr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&te(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:rt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Po;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Hr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&te(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=M(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.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 o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=iS(o.prefix),i=s[0],a=s[1],c=s[2],l=s[3],u=c===He.code?He:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(o.data,{truncate:l});d.then!=null&&(d=await d);let f=K.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:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:o.data}});let h=M(f.multihash.bytes,"base64"),p=this.wants.get(h);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=K.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===$r.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Po(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var fp=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 up(e),this.network=new sp(e,t),this.peerWantLists=new lp({...e,network:this.network},t),this.wantList=new dp({...e,network:this.network},t)}createSession(e={}){return oS({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=de([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new R("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.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(),await this.network.stop()}};var hp=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new fp(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(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!yr(o.detail))return;t.onProgress(new R("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new R("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new R("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new R("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function aS(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new hp(n,e);await ht(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}async function*fd(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 pp=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Ic(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),Ca(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new pp("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Zi=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},en=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var mp={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},gp=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new mt({concurrency:t.concurrentRequests??mp.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??mp.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??mp.cacheName,this.cacheTTL=t.cacheTTL??mp.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),o=de([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;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:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new Zi("Request does not conform to schema or semantic constraints"):new en(`Unexpected status code: ${l.status}`)}let u=l.headers.get("Content-Type");if(u==null)throw new en("No Content-Type header received");if(l.body==null){if(u!=="application/x-ndjson")throw new en("Routing response had no body");return}if(u.startsWith("application/json")){let f=(await l.json()).Providers??[];for(let h of f){let p=this.#e(h);p!=null&&(a++,yield p)}}else if(u.includes("application/x-ndjson"))for await(let d of Ic(fd(l.body))){let f=this.#e(d);f!=null&&(a++,yield f)}else throw new en(`Unsupported Content-Type: ${u}`)}finally{o.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),o=de([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;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:o});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 en("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let d=(await c.json()).Peers??[];for(let f of d){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Ic(fd(c.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(K.asCID(e)===e||e instanceof K)n=e.toV1().toString();else throw new A("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=de([this.shutDownController.signal,o,t.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;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:s});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 en("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await l.json()).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else for await(let d of Ic(fd(l.body))){let f=this.#e(d);f!=null&&(yield f)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.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),o=de([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let c=await this.#r(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new Te("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 en(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new Te("No matching records found");if(c.body==null)throw new en("GET ipns response had no body");let u=await c.arrayBuffer();return new Uint8Array(u,0,u.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=de([this.shutDownController.signal,o,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 i.promise;let l=await this.#r(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ee(t),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new en("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(G)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:K.createV1(114,TU(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),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 this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}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 TU(r){let e=ge.baseDecode(r);return Ee(e)}function CU(r){return r[Symbol.asyncIterator]!=null}function kU(r){if(CU(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var yp=kU;var wp=O("/ipns/");function cS(r){return te(r.subarray(0,wp.byteLength),wp)}var bp=class{client;constructor(e){this.client=e}get[ri](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async*findProviders(e,t={}){try{yield*Kt(this.client.getProviders(e,t),n=>({id:vt(n.ID),multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Te)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!cS(e))return;let o=Ee(e.slice(wp.length)),s=K.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!cS(e))throw new Te("Not found");let n=Ee(e.slice(wp.length)),o=K.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new Te("Not found"):s}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},xp=class{client;constructor(e){this.client=e}get[ai](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async findPeer(e,t={}){let n=await yp(this.client.getPeers(e.toCID(),t));if(n!=null)return{id:vt(n.ID),multiaddrs:n.Addrs??[]};throw new Te("Not found")}async*getClosestPeers(e,t={}){let n;try{n=K.decode(e)}catch{try{n=K.createV1(114,ze.decode(e))}catch{n=K.createV1(po,Ze.digest(e))}}for await(let o of this.client.getClosestPeers(n,t))yield{id:vt(o.ID),multiaddrs:o.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};function Ep(r){return e=>new gp(e,r)}function lS(r){return e=>new bp(Ep(r)(e))}function uS(r){return e=>new xp(Ep(r)(e))}var vp=O("/ipns/");function dS(r){return te(r.subarray(0,vp.byteLength),vp)}var Sp=class{name="delegated-http-router";client;constructor(e,t){this.client=Ep(t)(e)}async provide(e,t){}async cancelReprovide(e,t){}async*findProviders(e,t){yield*Kt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(e,t,n){if(!dS(e))return;let o=Ee(e.slice(vp.length)),s=K.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!dS(e))throw new Te("Not found");let n=Ee(e.slice(vp.length)),o=K.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new Te("Not found"):s}}async findPeer(e,t){let n=await yp(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Te("Not found")}async*getClosestPeers(e,t){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function hd(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function fS(r){return e=>new Sp(e,hd(r))}var hS="[a-fA-F\\d:]",Cs=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${hS})|(?<=${hS})(?=\\s|$))`:"",Cn="(?: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}",bt="[a-fA-F\\d]{1,4}",Ap=`
|
|
12
|
+
${e}[Error list was empty]`,t.trim()}return aE(r,e)}je.formatters.e=r=>r==null?"undefined":lE(r);function PB(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 tc(r){return{forComponent(e){return rc(e,r)}}}function rc(r,e){let t=PB(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=je(`${r}:trace`,e)),Object.assign(je(r,e),{error:je(`${r}:error`,e),trace:t,newScope:n=>rc(`${r}:${n}`,e)})}function cE(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var uE=Symbol.for("sindresorhus/unlimited-timeout#brand");function dE(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[uE]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let s=performance.now()+e,i=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||r(...t)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,s-c);i(l)},2147483647),n&&o.id?.unref?.()))};return i(e),o}function fE(r){!r||typeof r!="object"||!r[uE]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var LB=new WeakMap;function DB({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(o.reason)},u=()=>{o&&o.removeEventListener("abort",l)},d=new Promise((f,h)=>{i=()=>{u(),f(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",l,{once:!0}),LB.set(d,()=>{c(s),s=null,i()}),d}}var RB=DB({setTimeout:dE,clearTimeout:fE}),hE=RB;var Xt=class extends mt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var _1=class extends mt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var nc=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 Z4}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);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(o,i.consumedPoints,this.blockDuration)),new Zh("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,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)}},Z4=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,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 oc(r,e,t){let n,o,s=!1;function i(){let l={signal:o.signal},u;t?.timeout!=null&&(u=de([o.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),s=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,!o.signal.aborted&&(n=setTimeout(i,e))})}let a=bo(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:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var e6=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 gt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new e6({name:e,metrics:t}):n=new Map,n}var sc=class extends le{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=Nt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=$e.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=qe(),i={promise:s.promise,observers:1,queryFilter:Nt(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 mt({concurrency:this.maxProviders});l.addEventListener("failure",f=>{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,s.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)];this.evict(h)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),s.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 Ue(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&&s.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=()=>{s.reject(new nr(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await s.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 o=qe(),s=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",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.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",s,t,this.providers.length),this.providers.length<t)throw new au(`Found ${s} 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),o.reject(i)}),o.promise}};var P1=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Nu=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},L1=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},vo=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},D1=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},R1=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Ou=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};function NB(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ic=NB;function OB(r){return r[Symbol.asyncIterator]!=null}function BB(r,e){let t=0;if(OB(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=ic(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Br=BB;function MB(r){return r[Symbol.asyncIterator]!=null}function UB(r){if(MB(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ke([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ke(e,t)}var N1=UB;function O1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*FB(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],s=K.asCID(n);s!=null?yield[o.join("/"),s]:typeof n=="object"&&(yield*t6(n,o))}else{let t=K.asCID(e);t!=null?yield[r.join("/"),t]:yield*t6(e,r)}}function*t6(r,e){if(r==null||r instanceof Uint8Array)return;let t=K.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let s=[...e,n];yield*FB(s,o)}}function*$B(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&K.asCID(n)==null&&(yield*r6(n,o))}else yield*r6(e,r)}function*r6(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&K.asCID(n)==null&&(yield*$B(o,n))}}function KB(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=K.asCID(t);if(s!=null)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}var n6=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:O1(),bytes:O1(),value:O1(),asBlock:O1()})}links(){return t6(this.value,[])}tree(){return r6(this.value,[])}get(e="/"){return KB(this.value,e.split("/").filter(Boolean))}};function pE({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new n6({cid:e,bytes:r,value:o})}function i6(r){return e=>new s6(e,r)}var o6=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),o=Br(n.toGenerator(t),c=>c!=null),s=!1,i=t?.depth??1/0,a=async c=>{let l=c.cid,u=await N1(this.components.blockstore.get(l,c)),d=pE({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=>{s||o.throw(h)});return{block:d,depth:c.depth,path:c.path}};n.add(a,{...t,cid:e,depth:0,path:[e]}).catch(c=>{s||o.throw(c)});try{yield*o}finally{s=!0,n.abort()}}},s6=class extends o6{getQueue(){return new mt({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}};function ac(r){return r==null?!1:K.asCID(r)!=null}function gs(r){return r?.then!=null}var mE="1.2.840.10045.3.1.7",gE="1.3.132.0.34",yE="1.3.132.0.35";async function wE(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 bE(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,ee(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function xE(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,ee(e),ee(t.subarray()));return n?.signal?.throwIfAborted(),s}var VB=parseInt("11111",2),a6=parseInt("10000000",2),HB=parseInt("01111111",2),EE={0:Bu,1:Bu,2:qB,3:GB,4:jB,5:WB,6:zB,16:Bu,22:Bu,48:Bu};function Jr(r,e={offset:0}){let t=r[e.offset]&VB;if(e.offset++,EE[t]!=null)return EE[t](r,e);throw new Error("No decoder for tag "+t)}function Mu(r,e){let t=0;if((r[e.offset]&a6)===a6){let n=r[e.offset]&HB,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Bu(r,e){Mu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Jr(r,e);if(n===null)break;t.push(n)}return t}function qB(r,e){let t=Mu(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function zB(r,e){let t=Mu(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${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 WB(r,e){return e.offset++,null}function GB(r,e){let t=Mu(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function jB(r,e){let t=Mu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function YB(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function B1(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=YB(r.byteLength);return new Y(Uint8Array.from([e.byteLength|a6]),e)}function ur(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),B1(e),e)}function Uu(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),B1(t),t)}function vE(r){return new Y(Uint8Array.from([4]),B1(r),r)}function En(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),B1(t),t)}var XB=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),QB=Uint8Array.from([6,5,43,129,4,0,34]),JB=Uint8Array.from([6,5,43,129,4,0,35]),SE={ext:!0,kty:"EC",crv:"P-256"},AE={ext:!0,kty:"EC",crv:"P-384"},IE={ext:!0,kty:"EC",crv:"P-521"},cc=32,lc=48,uc=66;function TE(r){let e=Jr(r);return c6(e)}function c6(r){let e=r[1],t=M(e,"base64url"),n=r[2][1][0],o=1,s,i;if(e.byteLength===cc)return s=M(n.subarray(o,o+cc),"base64url"),i=M(n.subarray(o+cc),"base64url"),new Ri({...SE,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===lc)return s=M(n.subarray(o,o+lc),"base64url"),i=M(n.subarray(o+lc),"base64url"),new Ri({...AE,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===uc)return s=M(n.subarray(o,o+uc),"base64url"),i=M(n.subarray(o+uc),"base64url"),new Ri({...IE,key_ops:["sign"],d:t,x:s,y:i});throw new A(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function l6(r){let e=Jr(r);return CE(e)}function CE(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===cc*2+1)return n=M(e.subarray(t,t+cc),"base64url"),o=M(e.subarray(t+cc),"base64url"),new Di({...SE,key_ops:["verify"],x:n,y:o});if(e.byteLength===lc*2+1)return n=M(e.subarray(t,t+lc),"base64url"),o=M(e.subarray(t+lc),"base64url"),new Di({...AE,key_ops:["verify"],x:n,y:o});if(e.byteLength===uc*2+1)return n=M(e.subarray(t,t+uc),"base64url"),o=M(e.subarray(t+uc),"base64url"),new Di({...IE,key_ops:["verify"],x:n,y:o});throw new A(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function kE(r){return En([ur(Uint8Array.from([1])),vE(O(r.d??"","base64url")),En([PE(r.crv)],160),En([Uu(new Y(Uint8Array.from([4]),O(r.x??"","base64url"),O(r.y??"","base64url")))],161)]).subarray()}function _E(r){return En([ur(Uint8Array.from([1])),En([PE(r.crv)],160),En([Uu(new Y(Uint8Array.from([4]),O(r.x??"","base64url"),O(r.y??"","base64url")))],161)]).subarray()}function PE(r){if(r==="P-256")return XB;if(r==="P-384")return QB;if(r==="P-521")return JB;throw new A(`Invalid curve ${r}`)}async function LE(r="P-256"){let e=await wE(r);return new Ri(e.privateKey)}var Di=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=_E(this.jwk)),this._raw}toMultihash(){return Ze.digest(Lt(this))}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async verify(e,t,n){return xE(this.jwk,t,e,n)}},Ri=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Di({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=kE(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}async sign(e,t){return bE(this.jwk,e,t)}};function u6(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function xr(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ut(r,e,t=""){let n=u6(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Ao(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(xr(r.outputLen),xr(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function dc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function M1(r,e){Ut(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Qt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ni(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function vn(r,e){return r<<32-e|r>>>e}function U1(r,e){return r<<e|r>>>32-e>>>0}var RE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ZB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function F1(r){if(Ut(r),RE)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=ZB[r[t]];return e}var So={_0:48,_9:57,A:65,F:70,a:97,f:102};function DE(r){if(r>=So._0&&r<=So._9)return r-So._0;if(r>=So.A&&r<=So.F)return r-(So.A-10);if(r>=So.a&&r<=So.f)return r-(So.a-10)}function Fu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(RE)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=DE(r.charCodeAt(s)),a=DE(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}var eM=async()=>{};async function NE(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await eM(),n+=s)}}function tM(r){if(typeof r!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function d6(r,e=""){return typeof r=="string"?tM(r):Ut(r,void 0,e)}function f6(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ut(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function OE(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new TypeError("options must be object or undefined");return Object.assign(r,e)}function $u(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function BE(r=32){xr(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 h6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function $1(r,e,t){return r&e^~r&t}function K1(r,e,t){return r&e^r&t^e&t}var Oi=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ni(this.buffer)}update(e){dc(this),Ut(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Ni(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dc(this),M1(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Qt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ni(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Io=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ft=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var V1=BigInt(4294967295),ME=BigInt(32);function rM(r,e=!1){return e?{h:Number(r&V1),l:Number(r>>ME&V1)}:{h:Number(r>>ME&V1)|0,l:Number(r&V1)|0}}function UE(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=rM(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var p6=(r,e,t)=>r>>>t,m6=(r,e,t)=>r<<32-t|e>>>t,Bi=(r,e,t)=>r>>>t|e<<32-t,Mi=(r,e,t)=>r<<32-t|e>>>t,Ku=(r,e,t)=>r<<64-t|e>>>t-32,Vu=(r,e,t)=>r>>>t-32|e<<64-t;function Vn(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var FE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),$E=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,KE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),VE=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,HE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),qE=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var oM=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]),ys=new Uint32Array(64),g6=class extends Oi{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)ys[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=ys[d-15],h=ys[d-2],p=vn(f,7)^vn(f,18)^f>>>3,y=vn(h,17)^vn(h,19)^h>>>10;ys[d]=y+ys[d-7]+p+ys[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=vn(a,6)^vn(a,11)^vn(a,25),h=u+f+$1(a,c,l)+oM[d]+ys[d]|0,y=(vn(n,2)^vn(n,13)^vn(n,22))+K1(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+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,o,s,i,a,c,l,u)}roundClean(){Qt(ys)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Qt(this.buffer)}},y6=class extends g6{A=Io[0]|0;B=Io[1]|0;C=Io[2]|0;D=Io[3]|0;E=Io[4]|0;F=Io[5]|0;G=Io[6]|0;H=Io[7]|0;constructor(){super(32)}};var zE=UE(["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))),sM=zE[0],iM=zE[1],ws=new Uint32Array(80),bs=new Uint32Array(80),w6=class extends Oi{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:y,Hl:g}=this;return[e,t,n,o,s,i,a,c,l,u,d,f,h,p,y,g]}set(e,t,n,o,s,i,a,c,l,u,d,f,h,p,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|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=y|0,this.Hl=g|0}process(e,t){for(let x=0;x<16;x++,t+=4)ws[x]=e.getUint32(t),bs[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let E=ws[x-15]|0,S=bs[x-15]|0,T=Bi(E,S,1)^Bi(E,S,8)^p6(E,S,7),I=Mi(E,S,1)^Mi(E,S,8)^m6(E,S,7),C=ws[x-2]|0,U=bs[x-2]|0,j=Bi(C,U,19)^Ku(C,U,61)^p6(C,U,6),z=Mi(C,U,19)^Vu(C,U,61)^m6(C,U,6),v=KE(I,z,bs[x-7],bs[x-16]),D=VE(v,T,j,ws[x-7],ws[x-16]);ws[x]=D|0,bs[x]=v|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:y,Gl:g,Hh:m,Hl:w}=this;for(let x=0;x<80;x++){let E=Bi(d,f,14)^Bi(d,f,18)^Ku(d,f,41),S=Mi(d,f,14)^Mi(d,f,18)^Vu(d,f,41),T=d&h^~d&y,I=f&p^~f&g,C=HE(w,S,I,iM[x],bs[x]),U=qE(C,m,E,T,sM[x],ws[x]),j=C|0,z=Bi(n,o,28)^Ku(n,o,34)^Ku(n,o,39),v=Mi(n,o,28)^Vu(n,o,34)^Vu(n,o,39),D=n&s^n&a^s&a,L=o&i^o&c^i&c;m=y|0,w=g|0,y=h|0,g=p|0,h=d|0,p=f|0,{h:d,l:f}=Vn(l|0,u|0,U|0,j|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=FE(j,v,L);n=$E(_,U,z,D),o=_|0}({h:n,l:o}=Vn(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Vn(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Vn(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Vn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Vn(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=Vn(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:g}=Vn(this.Gh|0,this.Gl|0,y|0,g|0),{h:m,l:w}=Vn(this.Hh|0,this.Hl|0,m|0,w|0),this.set(n,o,s,i,a,c,l,u,d,f,h,p,y,g,m,w)}roundClean(){Qt(ws,bs)}destroy(){this.destroyed=!0,Qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},b6=class extends w6{Ah=Ft[0]|0;Al=Ft[1]|0;Bh=Ft[2]|0;Bl=Ft[3]|0;Ch=Ft[4]|0;Cl=Ft[5]|0;Dh=Ft[6]|0;Dl=Ft[7]|0;Eh=Ft[8]|0;El=Ft[9]|0;Fh=Ft[10]|0;Fl=Ft[11]|0;Gh=Ft[12]|0;Gl=Ft[13]|0;Hh=Ft[14]|0;Hl=Ft[15]|0;constructor(){super(64)}};var Zr=$u(()=>new y6,h6(1));var Hn=$u(()=>new b6,h6(3));var ye=(r,e,t)=>Ut(r,e,t),E6=xr,fc=F1,xt=(...r)=>f6(...r),hc=r=>Fu(r),Ui=u6,Fi=r=>BE(r),q1=BigInt(0),x6=BigInt(1);function Sn(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function z1(r){if(typeof r=="bigint"){if(!H1(r))throw new RangeError("positive bigint expected, got "+r)}else E6(r);return r}function An(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 Hu(r){let e=z1(r).toString(16);return e.length&1?"0"+e:e}function WE(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?q1:BigInt("0x"+r)}function $i(r){return WE(F1(r))}function Mr(r){return WE(F1(xs(Ut(r)).reverse()))}function W1(r,e){if(xr(e),e===0)throw new RangeError("zero length");r=z1(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Fu(t.padStart(e*2,"0"))}function qu(r,e){return W1(r,e).reverse()}function GE(r,e){if(r=ye(r),e=ye(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function xs(r){return Uint8Array.from(ye(r))}function G1(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var H1=r=>typeof r=="bigint"&&q1<=r;function aM(r,e,t){return H1(r)&&H1(e)&&H1(t)&&e<=r&&r<t}function To(r,e,t,n){if(!aM(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function pc(r){if(r<q1)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>q1;r>>=x6,e+=1);return e}var zu=r=>(x6<<BigInt(r))-x6;function jE(r,e,t){if(xr(r,"hashLen"),xr(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),s=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=(...g)=>t(l,xt(c,...g)),h=(g=o)=>{l=f(s,g),c=f(),g.length!==0&&(l=f(i,g),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,m=[];for(;g<e;){c=f();let w=c.slice();m.push(w),g+=c.length}return xt(...m)};return(g,m)=>{d(),h(g);let w;for(;(w=m(p()))===void 0;)h();return d(),w}}function Ur(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var v6=()=>{throw new Error("not implemented")};var $t=BigInt(0),at=BigInt(1),Ki=BigInt(2),JE=BigInt(3),ZE=BigInt(4),ev=BigInt(5),cM=BigInt(7),tv=BigInt(8),lM=BigInt(9),rv=BigInt(16);function tt(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 Ye(r,e,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 YE(r,e){if(r===$t)throw new Error("invert: expected non-zero number");if(e<=$t)throw new Error("invert: expected positive modulus, got "+e);let t=tt(r,e),n=e,o=$t,s=at,i=at,a=$t;for(;t!==$t;){let l=n/t,u=n-t*l,d=o-i*l,f=s-a*l;n=t,t=u,o=i,s=a,i=d,a=f}if(n!==at)throw new Error("invert: does not exist");return tt(o,e)}function S6(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function nv(r,e){let t=r,n=(t.ORDER+at)/ZE,o=t.pow(e,n);return S6(t,o,e),o}function uM(r,e){let t=r,n=(t.ORDER-ev)/tv,o=t.mul(e,Ki),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Ki),s),c=t.mul(i,t.sub(a,t.ONE));return S6(t,c,e),c}function dM(r){let e=mc(r),t=ov(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+cM)/rv;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,n),f=l.mul(u,o),h=l.mul(u,s),p=l.eql(l.sqr(d),c),y=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,y);let g=l.eql(l.sqr(d),c),m=l.cmov(u,d,g);return S6(l,m,c),m})}function ov(r){if(r<JE)throw new Error("sqrt is not defined for small field");let e=r-at,t=0;for(;e%Ki===$t;)e/=Ki,t++;let n=Ki,o=mc(r);for(;XE(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return nv;let s=o.pow(n,e),i=(e+at)/Ki;return function(c,l){let u=c;if(u.is0(l))return l;if(XE(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,s),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let y=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(y++,g=u.sqr(g),y===d)throw new Error("Cannot find square root");let m=at<<BigInt(d-y-1),w=u.pow(f,m);d=y,f=u.sqr(w),h=u.mul(h,f),p=u.mul(p,w)}return p}}function fM(r){return r%ZE===JE?nv:r%tv===ev?uM:r%rv===lM?dM(r):ov(r)}var Co=(r,e)=>(tt(r,e)&at)===at,hM=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function A6(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=hM.reduce((n,o)=>(n[o]="function",n),e);if(Ur(r,t),An(r.BYTES,"BYTES"),An(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=at)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function pM(r,e,t){let n=r;if(t<$t)throw new Error("invalid exponent, negatives unsupported");if(t===$t)return n.ONE;if(t===at)return e;let o=n.ONE,s=e;for(;t>$t;)t&at&&(o=n.mul(o,s)),s=n.sqr(s),t>>=at;return o}function Wu(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function XE(r,e){let t=r,n=(t.ORDER-at)/Ki,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function mM(r,e){if(e!==void 0&&E6(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=pc(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var QE=new WeakMap,j1=class{ORDER;BITS;BYTES;isLE;ZERO=$t;ONE=at;_lengths;_mod;constructor(e,t={}){if(e<=at)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=mM(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return tt(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&at)===at}neg(e){return tt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return tt(e*e,this.ORDER)}add(e,t){return tt(e+t,this.ORDER)}sub(e,t){return tt(e-t,this.ORDER)}mul(e,t){return tt(e*t,this.ORDER)}pow(e,t){return pM(this,e,t)}div(e,t){return tt(e*YE(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 YE(e,this.ORDER)}sqrt(e){let t=QE.get(this);return t||QE.set(this,t=fM(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?qu(e,this.BYTES):W1(e,this.BYTES)}fromBytes(e,t=!1){ye(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Mr(e):$i(e);if(a&&(c=tt(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Wu(this,e)}cmov(e,t,n){return Sn(n,"condition"),n?t:e}};Object.freeze(j1.prototype);function mc(r,e={}){return new j1(r,e)}function sv(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=at)throw new Error("field order must be greater than 1");let e=pc(r-at);return Math.ceil(e/8)}function I6(r){let e=sv(r);return e+Math.ceil(e/2)}function T6(r,e,t=!1){ye(r);let n=r.length,o=sv(e),s=Math.max(I6(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Mr(r):$i(r),a=tt(i,e-at)+at;return t?qu(a,o):W1(a,o)}var gc=BigInt(0),Vi=BigInt(1);function Gu(r,e){let t=e.negate();return r?t:e}function Hi(r,e){let t=Wu(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function lv(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function C6(r,e){lv(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=zu(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function iv(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Vi);let l=e*n,u=l+Math.abs(a)-1,d=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:l}}var k6=new WeakMap,uv=new WeakMap;function _6(r){return uv.get(r)||1}function av(r){if(r!==gc)throw new Error("invalid wNAF")}var yc=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>gc;)t&Vi&&(n=n.add(o)),o=o.double(),t>>=Vi;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=C6(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=C6(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}=iv(n,a,i);n=c,u?s=s.add(Gu(f,t[h])):o=o.add(Gu(d,t[l]))}return av(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=C6(e,this.bits);for(let i=0;i<s.windows&&n!==gc;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=iv(n,i,s);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return av(n),o}getPrecomputes(e,t,n){let o=k6.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),k6.set(t,o))),o}cached(e,t,n){let o=_6(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=_6(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){lv(t,this.bits),uv.set(e,t),k6.delete(e)}hasCache(e){return _6(e)!==1}};function dv(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>gc||n>gc;)t&Vi&&(s=s.add(o)),n&Vi&&(i=i.add(o)),o=o.double(),t>>=Vi,n>>=Vi;return{p1:s,p2:i}}function cv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return A6(e),e}else return mc(r,{isLE:t})}function Y1(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>gc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=cv(e.p,t.Fp,n),s=cv(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function wc(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Es=BigInt(0),Dt=BigInt(1),P6=BigInt(2),gM=BigInt(8);function yM(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function fv(r,e={}){let t=e,n=Y1("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ur(t,{},{uvRatio:"function"});let c=P6<<BigInt(s.BYTES*8)-Dt,l=y=>o.create(y),u=t.uvRatio===void 0?(y,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,g))}}catch{return{isValid:!1,value:Es}}}:t.uvRatio;if(!yM(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(y,g,m=!1){let w=m?Dt:Es;return To("coordinate "+y,g,w,c),g}function f(y){if(!(y instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,Dt,l(i.Gx*i.Gy));static ZERO=new h(Es,Dt,Dt,Es);static Fp=o;static Fn=s;X;Y;Z;T;constructor(g,m,w,x){this.X=d("x",g),this.Y=d("y",m),this.Z=d("z",w,!0),this.T=d("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{x:m,y:w}=g||{};return d("x",m),d("y",w),new h(m,w,Dt,l(m*w))}static fromBytes(g,m=!1){let w=o.BYTES,{a:x,d:E}=i;g=xs(ye(g,w,"point")),Sn(m,"zip215");let S=xs(g),T=g[w-1];S[w-1]=T&-129;let I=Mr(S),C=m?c:o.ORDER;To("point.y",I,Es,C);let U=l(I*I),j=l(U-Dt),z=l(E*U-x),{isValid:v,value:D}=u(j,z);if(!v)throw new Error("bad point: invalid y coordinate");let L=(D&Dt)===Dt,_=(T&128)!==0;if(!m&&D===Es&&_)throw new Error("bad point: x=0 and x_0=1");return _!==L&&(D=l(-D)),h.fromAffine({x:D,y:I})}static fromHex(g,m=!1){return h.fromBytes(hc(g),m)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return p.createCache(this,g),m||this.multiply(P6),this}assertValidity(){let g=this,{a:m,d:w}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:x,Y:E,Z:S,T}=g,I=l(x*x),C=l(E*E),U=l(S*S),j=l(U*U),z=l(I*m),v=l(U*l(z+C)),D=l(j+l(w*l(I*C)));if(v!==D)throw new Error("bad point: equation left != right (1)");let L=l(x*E),_=l(S*T);if(L!==_)throw new Error("bad point: equation left != right (2)")}equals(g){f(g);let{X:m,Y:w,Z:x}=this,{X:E,Y:S,Z:T}=g,I=l(m*T),C=l(E*x),U=l(w*T),j=l(S*x);return I===C&&U===j}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:g}=i,{X:m,Y:w,Z:x}=this,E=l(m*m),S=l(w*w),T=l(P6*l(x*x)),I=l(g*E),C=m+w,U=l(l(C*C)-E-S),j=I+S,z=j-T,v=I-S,D=l(U*z),L=l(j*v),_=l(U*v),k=l(z*j);return new h(D,L,k,_)}add(g){f(g);let{a:m,d:w}=i,{X:x,Y:E,Z:S,T}=this,{X:I,Y:C,Z:U,T:j}=g,z=l(x*I),v=l(E*C),D=l(T*w*j),L=l(S*U),_=l((x+E)*(I+C)-z-v),k=L-D,N=L+D,F=l(v-m*z),P=l(_*k),$=l(N*F),H=l(_*F),Z=l(k*N);return new h(P,$,Z,H)}subtract(g){return f(g),this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:m,f:w}=p.cached(this,g,x=>Hi(h,x));return Hi(h,[m,w])[0]}multiplyUnsafe(g){if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Es?h.ZERO:this.is0()||g===Dt?this:p.unsafe(this,g,m=>Hi(h,m))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(g){let m=this,w=g,{X:x,Y:E,Z:S}=m,T=m.is0();w==null&&(w=T?gM:o.inv(S));let I=l(x*w),C=l(E*w),U=o.mul(S,w);if(T)return{x:Es,y:Dt};if(U!==Dt)throw new Error("invZ was invalid");return{x:I,y:C}}clearCofactor(){return a===Dt?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:m}=this.toAffine(),w=o.toBytes(m);return w[w.length-1]|=g&Dt?128:0,w}toHex(){return fc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new yc(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var X1=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){v6()}static fromHex(e){v6()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return fc(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function hv(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Ur(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(An(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?Fi:o.randomBytes,f=o.adjustScalarBytes===void 0?v=>v:o.adjustScalarBytes,h=o.domain===void 0?(v,D,L)=>{if(Sn(L,"phflag"),D.length||L)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function p(v){return c.create(Mr(v))}function y(v){let D=I.secretKey;ye(v,I.secretKey,"secretKey");let L=ye(n(v),2*D,"hashedSecretKey"),_=f(L.slice(0,D)),k=L.slice(D,2*D),N=p(_);return{head:_,prefix:k,scalar:N}}function g(v){let{head:D,prefix:L,scalar:_}=y(v),k=i.multiply(_),N=k.toBytes();return{head:D,prefix:L,scalar:_,point:k,pointBytes:N}}function m(v){return g(v).pointBytes}function w(v=Uint8Array.of(),...D){let L=xt(...D);return p(n(h(L,ye(v,void 0,"context"),!!s)))}function x(v,D,L={}){v=ye(v,void 0,"message"),s&&(v=s(v));let{prefix:_,scalar:k,pointBytes:N}=g(D),F=w(L.context,_,v),P=i.multiply(F).toBytes(),$=w(L.context,P,N,v),H=c.create(F+$*k);if(!c.isValid(H))throw new Error("sign failed: invalid s");let Z=xt(P,c.toBytes(H));return ye(Z,I.signature,"result")}let E={zip215:o.zip215};function S(v,D,L,_=E){let{context:k}=_,N=_.zip215===void 0?!!E.zip215:_.zip215,F=I.signature;v=ye(v,F,"signature"),D=ye(D,void 0,"message"),L=ye(L,I.publicKey,"publicKey"),N!==void 0&&Sn(N,"zip215"),s&&(D=s(D));let P=F/2,$=v.subarray(0,P),H=Mr(v.subarray(P,F)),Z,fe,ue;try{Z=r.fromBytes(L,N),fe=r.fromBytes($,N),ue=i.multiplyUnsafe(H)}catch{return!1}if(!N&&Z.isSmallOrder())return!1;let Ne=w(k,$,L,D);return fe.add(Z.multiplyUnsafe(Ne)).subtract(ue).clearCofactor().is0()}let T=a.BYTES,I={secretKey:T,publicKey:T,signature:2*T,seed:T};function C(v){return v=v===void 0?d(I.seed):v,ye(v,I.seed,"seed")}function U(v){return Ui(v)&&v.length===I.secretKey}function j(v,D){try{return!!r.fromBytes(v,D===void 0?E.zip215:D)}catch{return!1}}let z={getExtendedPublicKey:g,randomSecretKey:C,isValidSecretKey:U,isValidPublicKey:j,toMontgomery(v){let{y:D}=r.fromBytes(v),L=I.publicKey,_=L===32;if(!_&&L!==57)throw new Error("only defined for 25519 and 448");let k=_?a.div(Dt+D,Dt-D):a.div(D-Dt,D+Dt);return a.toBytes(k)},toMontgomerySecret(v){let D=I.secretKey;ye(v,D);let L=n(v.subarray(0,D));return f(L).subarray(0,D)}};return Object.freeze(I),Object.freeze(z),Object.freeze({keygen:wc(C,m),getPublicKey:m,sign:x,verify:S,utils:z,Point:r,lengths:I})}function ju(r,e){if(An(r),An(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function wM(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function bM(r){if(!Ui(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?G1(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function L6(r,e,t,n){ye(r),An(t),e=bM(e),e.length>255&&(e=n(xt(G1("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=xt(e,ju(e.length,1)),c=new Uint8Array(s),l=ju(t,2),u=new Array(i),d=n(xt(c,r,l,ju(0,1),a));u[0]=n(xt(d,ju(1,1),a));for(let h=1;h<i;h++){let p=[wM(d,u[h-1]),ju(h+1,1),a];u[h]=n(xt(...p))}return xt(...u).slice(0,t)}var pv="HashToScalar-";var Yu=BigInt(0),bc=BigInt(1),Q1=BigInt(2);function xM(r){return Ur(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function mv(r){let e=xM(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?Fi:i,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),h=a?Q1**BigInt(254):Q1**BigInt(447),p=a?BigInt(8)*Q1**BigInt(251)-bc:BigInt(4)*Q1**BigInt(445)-bc,y=h+p+bc,g=L=>tt(L,t),m=w(d);function w(L){return qu(g(L),u)}function x(L){let _=xs(ye(L,u,"uCoordinate"));return a&&(_[31]&=127),g(Mr(_))}function E(L){return Mr(o(xs(ye(L,u,"scalar"))))}function S(L,_){let k=j(x(_),E(L));if(k===Yu)throw new Error("invalid private or public key received");return w(k)}function T(L){return S(L,m)}let I=T,C=S;function U(L,_,k){let N=g(L*(_-k));return _=g(_-N),k=g(k+N),{x_2:_,x_3:k}}function j(L,_){To("u",L,Yu,t),To("scalar",_,h,y);let k=_,N=L,F=bc,P=Yu,$=L,H=bc,Z=Yu;for(let ue=BigInt(l-1);ue>=Yu;ue--){let Ne=k>>ue&bc;Z^=Ne,{x_2:F,x_3:$}=U(Z,F,$),{x_2:P,x_3:H}=U(Z,P,H),Z=Ne;let Oe=F+P,Be=g(Oe*Oe),Ie=F-P,Je=g(Ie*Ie),uo=Be-Je,ei=$+H,wa=$-H,Ul=g(wa*Oe),Fl=g(ei*Ie),hb=Ul+Fl,pb=Ul-Fl;$=g(hb*hb),H=g(N*g(pb*pb)),F=g(Be*Je),P=g(uo*(Be+g(f*uo)))}({x_2:F,x_3:$}=U(Z,F,$)),{x_2:P,x_3:H}=U(Z,P,H);let fe=s(P);return g(F*fe)}let z={secretKey:u,publicKey:u,seed:u},v=L=>(L=L===void 0?c(u):L,ye(L,z.seed,"seed"),L),D={randomSecretKey:v};return Object.freeze(z),Object.freeze(D),Object.freeze({keygen:wc(v,I),getSharedSecret:C,getPublicKey:I,scalarMult:S,scalarMultBase:T,utils:D,GuBytes:m.slice(),lengths:z})}var EM=BigInt(0),ko=BigInt(1),gv=BigInt(2),vM=BigInt(3),SM=BigInt(5),AM=BigInt(8),qi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),O6={p:qi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:AM,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function bv(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=qi,a=r*r%s*r%s,c=Ye(a,gv,s)*a%s,l=Ye(c,ko,s)*r%s,u=Ye(l,SM,s)*l%s,d=Ye(u,e,s)*u%s,f=Ye(d,t,s)*d%s,h=Ye(f,n,s)*f%s,p=Ye(h,o,s)*h%s,y=Ye(p,o,s)*h%s,g=Ye(y,e,s)*u%s;return{pow_p_5_8:Ye(g,gv,s)*r%s,b2:a}}function xv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var D6=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function B6(r,e){let t=qi,n=tt(e*e*e,t),o=tt(n*n*e,t),s=bv(r*o).pow_p_5_8,i=tt(r*n*s,t),a=tt(e*i*i,t),c=i,l=tt(i*D6,t),u=a===r,d=a===tt(-r,t),f=a===tt(-r*D6,t);return u&&(i=c),(d||f)&&(i=l),Co(i,t)&&(i=tt(-i,t)),{isValid:u||d,value:i}}var Ss=fv(O6,{uvRatio:B6}),vs=Ss.Fp,Ev=Ss.Fn;function IM(r){return hv(Ss,Hn,Object.assign({adjustScalarBytes:xv,zip215:!0},r))}var Xu=IM({});var Qu=(()=>{let r=qi;return mv({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=bv(e);return tt(Ye(t,vM,r)*n,r)},adjustScalarBytes:xv})})();var R6=D6,TM=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),CM=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kM=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),_M=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),yv=r=>B6(ko,r),PM=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),N6=r=>vs.create(Mr(r)&PM);function wv(r){let{d:e}=O6,t=qi,n=m=>vs.create(m),o=n(R6*r*r),s=n((o+ko)*kM),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=B6(s,a),u=n(l*r);Co(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let d=n(i*(o-ko)*_M-a),f=l*l,h=n((l+l)*a),p=n(d*TM),y=n(ko-f),g=n(ko+f);return new Ss(n(h*g),n(y*p),n(p*g),n(h*y))}var As=class r extends X1{static BASE=new r(Ss.BASE);static ZERO=new r(Ss.ZERO);static Fp=vs;static Fn=Ev;constructor(e){super(e)}static fromAffine(e){return new r(Ss.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ut(e,32);let{a:t,d:n}=O6,o=qi,s=E=>vs.create(E),i=N6(e);if(!GE(vs.toBytes(i),e)||Co(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ko+t*a),l=s(ko-t*a),u=s(c*c),d=s(l*l),f=s(t*n*u-d),{isValid:h,value:p}=yv(s(f*d)),y=s(p*l),g=s(p*y*f),m=s((i+i)*y);Co(m,o)&&(m=s(-m));let w=s(c*g),x=s(m*w);if(!h||Co(x,o)||w===EM)throw new Error("invalid ristretto255 encoding 2");return new r(new Ss(m,w,ko,x))}static fromHex(e){return r.fromBytes(Fu(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=qi,i=g=>vs.create(g),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=yv(i(a*l)),d=i(u*a),f=i(u*c),h=i(d*f*o),p;if(Co(o*h,s)){let g=i(t*R6),m=i(e*R6);e=g,t=m,p=i(d*CM)}else p=f;Co(e*h,s)&&(t=i(-t));let y=i((n-t)*p);return Co(y,s)&&(y=i(-y)),vs.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>vs.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(As.BASE);Object.freeze(As.ZERO);Object.freeze(As.prototype);Object.freeze(As);var LM=Object.freeze({Point:As,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=L6(r,t,64,Hn);return LM.deriveToCurve(n)},hashToScalar(r,e={DST:pv}){let t=L6(r,e.DST,64,Hn);return Ev.create(Mr(t))},deriveToCurve(r){Ut(r,64);let e=N6(r.subarray(0,32)),t=wv(e),n=N6(r.subarray(32,64)),o=wv(n);return new As(t.add(o))}});var Ju=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Zu=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},J1=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var yt={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new J1("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 zi=32,Fr=64,M6=32;var xc,vv=(async()=>{try{return await yt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Sv(){let r=Xu.utils.randomSecretKey(),e=Xu.getPublicKey(r);return{privateKey:BM(r,e),publicKey:e}}async function DM(r,e){let t;r.length===Fr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:M(r.subarray(32),"base64url"),d:M(t,"base64url"),ext:!0,key_ops:["sign"]},o=await yt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await yt.get().subtle.sign({name:"Ed25519"},o,ee(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function RM(r,e){let t=r.subarray(0,M6);return Xu.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Av(r,e){return xc==null&&(xc=await vv),xc?DM(r,e):RM(r,e)}async function NM(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await yt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await yt.get().subtle.verify({name:"Ed25519"},n,ee(e),ee(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function OM(r,e,t){return Xu.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Iv(r,e,t){return xc==null&&(xc=await vv),xc?NM(r,e,t):OM(r,e,t)}function BM(r,e){let t=new Uint8Array(Fr);for(let n=0;n<M6;n++)t[n]=r[n],t[M6+n]=e[n];return t}function Ec(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ed=class{type="Ed25519";raw;constructor(e){this.raw=Sc(e,zi)}toMultihash(){return Ze.digest(Lt(this))}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Iv(this.raw,t,e);return Ec(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},vc=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Sc(e,Fr),this.publicKey=new ed(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Av(this.raw,e);return Ec(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function U6(r){if(r.length>Fr){r=Sc(r,Fr+zi);let n=r.subarray(0,Fr),o=r.subarray(Fr,r.length);return new vc(n,o)}r=Sc(r,Fr);let e=r.subarray(0,Fr),t=r.subarray(zi);return new vc(e,t)}function F6(r){return r=Sc(r,zi),new ed(r)}async function Cv(){let{privateKey:r,publicKey:e}=Sv();return new vc(r,e)}function Sc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new A(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Fe||(Fe={}));var $6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})($6||($6={}));(function(r){r.codec=()=>et($6)})(Fe||(Fe={}));var qn;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Fe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(qn||(qn={}));var td;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Fe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(td||(td={}));var nd={};V(nd,{MAX_RSA_KEY_SIZE:()=>K6,generateRSAKeyPair:()=>X6,jwkToJWKKeyPair:()=>Lv,jwkToPkcs1:()=>$M,jwkToPkix:()=>z6,jwkToRSAPrivateKey:()=>Y6,pkcs1MessageToJwk:()=>H6,pkcs1MessageToRSAPrivateKey:()=>Z1,pkcs1ToJwk:()=>FM,pkcs1ToRSAPrivateKey:()=>W6,pkixMessageToJwk:()=>q6,pkixMessageToRSAPublicKey:()=>j6,pkixToJwk:()=>KM,pkixToRSAPublicKey:()=>G6});var Ac=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=nd.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return K.createV1(114,this._multihash)}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return Pv(this.jwk,t,e,n)}},rd=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=nd.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return _v(this.jwk,e,t)}};var K6=8192,V6=18,MM=1062,UM=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function FM(r){let e=Jr(r);return H6(e)}function H6(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function $M(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 A("JWK was missing components");return En([ur(Uint8Array.from([0])),ur(O(r.n,"base64url")),ur(O(r.e,"base64url")),ur(O(r.d,"base64url")),ur(O(r.p,"base64url")),ur(O(r.q,"base64url")),ur(O(r.dp,"base64url")),ur(O(r.dq,"base64url")),ur(O(r.qi,"base64url"))]).subarray()}function KM(r){let e=Jr(r,{offset:0});return q6(e)}function q6(r){let e=Jr(r[1],{offset:0});return{kty:"RSA",n:M(e[0],"base64url"),e:M(e[1],"base64url")}}function z6(r){if(r.n==null||r.e==null)throw new A("JWK was missing components");return En([UM,Uu(En([ur(O(r.n,"base64url")),ur(O(r.e,"base64url"))]))]).subarray()}function W6(r){let e=Jr(r);return Z1(e)}function Z1(r){let e=H6(r);return Y6(e)}function G6(r,e){if(r.byteLength>=MM)throw new fo("Key size is too large");let t=Jr(r,{offset:0});return j6(t,r,e)}function j6(r,e,t){let n=q6(r);if(t==null){let o=Zr(qn.encode({Type:Fe.RSA,Data:e}));t=sr(V6,o)}return new Ac(n,t)}function Y6(r){if(Rv(r)>K6)throw new A("Key size is too large");let e=Lv(r),t=Zr(qn.encode({Type:Fe.RSA,Data:z6(e.publicKey)})),n=sr(V6,t);return new rd(e.privateKey,new Ac(e.publicKey,n))}async function X6(r){if(r>K6)throw new A("Key size is too large");let e=await Dv(r),t=Zr(qn.encode({Type:Fe.RSA,Data:z6(e.publicKey)})),n=sr(V6,t);return new rd(e.privateKey,new Ac(e.publicKey,n))}function Lv(r){if(r==null)throw new A("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Dv(r,e){let t=await yt.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 VM(t,e);return{privateKey:n[0],publicKey:n[1]}}async function _v(r,e,t){let n=await yt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await yt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,ee(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Pv(r,e,t,n){let o=await yt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await yt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,ee(e),ee(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function VM(r,e){if(r.privateKey==null||r.publicKey==null)throw new A("Private and public key are required");let t=await Promise.all([yt.get().subtle.exportKey("jwk",r.privateKey),yt.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Rv(r){if(r.kty!=="RSA")throw new A("invalid key type");if(r.n==null)throw new A("invalid key modulus");return O(r.n,"base64url").length*8}var ep=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ao(e),Ut(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Qt(o)}update(e){return dc(this),this.iHash.update(e),this}digestInto(e){dc(this),M1(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Wi=(()=>{let r=((e,t,n)=>new ep(e,t).update(n).digest());return r.create=(e,t)=>new ep(e,t),r})();var Nv=(r,e)=>(r+(r>=0?e:-e)/Ov)/e;function HM(r,e,t){To("scalar",r,zn,t);let[[n,o],[s,i]]=e,a=Nv(i*r,t),c=Nv(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,d=l<zn,f=u<zn;d&&(l=-l),f&&(u=-u);let h=zu(Math.ceil(pc(t)/2))+Is;if(l<zn||l>=h||u<zn||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function J6(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Q6(r,e){Ur(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Sn(t.lowS,"lowS"),Sn(t.prehash,"prehash"),t.format!==void 0&&J6(t.format),t}var Z6=class extends Error{constructor(e=""){super(e)}},In={Err:Z6,_tlv:{encode:(r,e)=>{let{Err:t}=In;if(An(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Hu(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Hu(o.length/2|128):"";return Hu(r)+s+o+e},decode(r,e){let{Err:t}=In;e=ye(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)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}=In;if(z1(r),r<zn)throw new e("integer: negative integers are not allowed");let t=Hu(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}=In;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 $i(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=In,o=ye(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=In,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(In._tlv);Object.freeze(In._int);Object.freeze(In);var zn=BigInt(0),Is=BigInt(1),Ov=BigInt(2),tp=BigInt(3),qM=BigInt(4);function Bv(r,e={}){let t=Y1("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Ur(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Uv(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(z,v,D){if(l&&v.is0())return Uint8Array.of(0);let{x:L,y:_}=v.toAffine(),k=n.toBytes(L);if(Sn(D,"isCompressed"),D){d();let N=!n.isOdd(_);return xt(Mv(N),k)}else return xt(Uint8Array.of(4),k,n.toBytes(_))}function h(z){ye(z,void 0,"Point");let{publicKey:v,publicKeyUncompressed:D}=u,L=z.length,_=z[0],k=z.subarray(1);if(l&&L===1&&_===0)return{x:n.ZERO,y:n.ZERO};if(L===v&&(_===2||_===3)){let N=n.fromBytes(k);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let F=g(N),P;try{P=n.sqrt(F)}catch(Z){let fe=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+fe)}d();let $=n.isOdd(P);return(_&1)===1!==$&&(P=n.neg(P)),{x:N,y:P}}else if(L===D&&_===4){let N=n.BYTES,F=n.fromBytes(k.subarray(0,N)),P=n.fromBytes(k.subarray(N,N*2));if(!m(F,P))throw new Error("bad point: is not on curve");return{x:F,y:P}}else throw new Error(`bad point: got length ${L}, expected compressed=${v} or uncompressed=${D}`)}let p=e.toBytes===void 0?f:e.toBytes,y=e.fromBytes===void 0?h:e.fromBytes;function g(z){let v=n.sqr(z),D=n.mul(v,z);return n.add(n.add(D,n.mul(z,s.a)),s.b)}function m(z,v){let D=n.sqr(v),L=g(z);return n.eql(D,L)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,tp),qM),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,x)))throw new Error("bad curve params: a or b");function E(z,v,D=!1){if(!n.isValid(v)||D&&n.is0(v))throw new Error(`bad point coordinate ${z}`);return v}function S(z){if(!(z instanceof C))throw new Error("Weierstrass Point expected")}function T(z){if(!c||!c.basises)throw new Error("no endo");return HM(z,c.basises,o.ORDER)}function I(z,v,D,L,_){return D=new C(n.mul(D.X,z),D.Y,D.Z),v=Gu(L,v),D=Gu(_,D),v.add(D)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(v,D,L){this.X=E("x",v),this.Y=E("y",D,!0),this.Z=E("z",L),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){let{x:D,y:L}=v||{};if(!v||!n.isValid(D)||!n.isValid(L))throw new Error("invalid affine point");if(v instanceof C)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(L)?C.ZERO:new C(D,L,n.ONE)}static fromBytes(v){let D=C.fromAffine(y(ye(v,void 0,"point")));return D.assertValidity(),D}static fromHex(v){return C.fromBytes(hc(v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,D=!0){return j.createCache(this,v),D||this.multiply(tp),this}assertValidity(){let v=this;if(v.is0()){if(e.allowInfinityPoint&&n.is0(v.X)&&n.eql(v.Y,n.ONE)&&n.is0(v.Z))return;throw new Error("bad point: ZERO")}let{x:D,y:L}=v.toAffine();if(!n.isValid(D)||!n.isValid(L))throw new Error("bad point: x or y not field elements");if(!m(D,L))throw new Error("bad point: equation left != right");if(!v.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:v}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(v)}equals(v){S(v);let{X:D,Y:L,Z:_}=this,{X:k,Y:N,Z:F}=v,P=n.eql(n.mul(D,F),n.mul(k,_)),$=n.eql(n.mul(L,F),n.mul(N,_));return P&&$}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:v,b:D}=s,L=n.mul(D,tp),{X:_,Y:k,Z:N}=this,F=n.ZERO,P=n.ZERO,$=n.ZERO,H=n.mul(_,_),Z=n.mul(k,k),fe=n.mul(N,N),ue=n.mul(_,k);return ue=n.add(ue,ue),$=n.mul(_,N),$=n.add($,$),F=n.mul(v,$),P=n.mul(L,fe),P=n.add(F,P),F=n.sub(Z,P),P=n.add(Z,P),P=n.mul(F,P),F=n.mul(ue,F),$=n.mul(L,$),fe=n.mul(v,fe),ue=n.sub(H,fe),ue=n.mul(v,ue),ue=n.add(ue,$),$=n.add(H,H),H=n.add($,H),H=n.add(H,fe),H=n.mul(H,ue),P=n.add(P,H),fe=n.mul(k,N),fe=n.add(fe,fe),H=n.mul(fe,ue),F=n.sub(F,H),$=n.mul(fe,Z),$=n.add($,$),$=n.add($,$),new C(F,P,$)}add(v){S(v);let{X:D,Y:L,Z:_}=this,{X:k,Y:N,Z:F}=v,P=n.ZERO,$=n.ZERO,H=n.ZERO,Z=s.a,fe=n.mul(s.b,tp),ue=n.mul(D,k),Ne=n.mul(L,N),Oe=n.mul(_,F),Be=n.add(D,L),Ie=n.add(k,N);Be=n.mul(Be,Ie),Ie=n.add(ue,Ne),Be=n.sub(Be,Ie),Ie=n.add(D,_);let Je=n.add(k,F);return Ie=n.mul(Ie,Je),Je=n.add(ue,Oe),Ie=n.sub(Ie,Je),Je=n.add(L,_),P=n.add(N,F),Je=n.mul(Je,P),P=n.add(Ne,Oe),Je=n.sub(Je,P),H=n.mul(Z,Ie),P=n.mul(fe,Oe),H=n.add(P,H),P=n.sub(Ne,H),H=n.add(Ne,H),$=n.mul(P,H),Ne=n.add(ue,ue),Ne=n.add(Ne,ue),Oe=n.mul(Z,Oe),Ie=n.mul(fe,Ie),Ne=n.add(Ne,Oe),Oe=n.sub(ue,Oe),Oe=n.mul(Z,Oe),Ie=n.add(Ie,Oe),ue=n.mul(Ne,Ie),$=n.add($,ue),ue=n.mul(Je,Ie),P=n.mul(Be,P),P=n.sub(P,ue),ue=n.mul(Be,Ne),H=n.mul(Je,H),H=n.add(H,ue),new C(P,$,H)}subtract(v){return S(v),this.add(v.negate())}is0(){return this.equals(C.ZERO)}multiply(v){let{endo:D}=e;if(!o.isValidNot0(v))throw new RangeError("invalid scalar: out of range");let L,_,k=N=>j.cached(this,N,F=>Hi(C,F));if(D){let{k1neg:N,k1:F,k2neg:P,k2:$}=T(v),{p:H,f:Z}=k(F),{p:fe,f:ue}=k($);_=Z.add(ue),L=I(D.beta,H,fe,N,P)}else{let{p:N,f:F}=k(v);L=N,_=F}return Hi(C,[L,_])[0]}multiplyUnsafe(v){let{endo:D}=e,L=this,_=v;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===zn||L.is0())return C.ZERO;if(_===Is)return L;if(j.hasCache(this))return this.multiply(_);if(D){let{k1neg:k,k1:N,k2neg:F,k2:P}=T(_),{p1:$,p2:H}=dv(C,L,N,P);return I(D.beta,$,H,k,F)}else return j.unsafe(L,_)}toAffine(v){let D=this,L=v,{X:_,Y:k,Z:N}=D;if(n.eql(N,n.ONE))return{x:_,y:k};let F=D.is0();L==null&&(L=F?n.ONE:n.inv(N));let P=n.mul(_,L),$=n.mul(k,L),H=n.mul(N,L);if(F)return{x:n.ZERO,y:n.ZERO};if(!n.eql(H,n.ONE))throw new Error("invZ was invalid");return{x:P,y:$}}isTorsionFree(){let{isTorsionFree:v}=e;return i===Is?!0:v?v(C,this):j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:v}=e;return i===Is?this:v?v(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Is?this.is0():this.clearCofactor().is0()}toBytes(v=!0){return Sn(v,"isCompressed"),this.assertValidity(),p(C,this,v)}toHex(v=!0){return fc(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=o.BITS,j=new yc(C,e.endo?Math.ceil(U/2):U);return U>=8&&C.BASE.precompute(8),Object.freeze(C.prototype),Object.freeze(C),C}function Mv(r){return Uint8Array.of(r?2:3)}function Uv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function zM(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Fi:e.randomBytes,o=Object.assign(Uv(r.Fp,t),{seed:Math.max(I6(t.ORDER),16)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:y,publicKeyUncompressed:g}=o;try{let m=h.length;return p===!0&&m!==y||p===!1&&m!==g?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,T6(ye(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:g}=o,m=t._lengths;if(!Ui(h))return;let w=ye(h,void 0,"key").length,x=w===y||w===g,E=w===p||!!m?.includes(w);if(!(x&&E))return x}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h);return r.fromBytes(p).multiply(g).toBytes(y)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},f=wc(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:o})}function Fv(r,e,t={}){let n=e;Ao(n),Ur(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Fi:t.randomBytes,s=t.hmac===void 0?(_,k)=>Wi(n,_,k):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=zM(r,t),y={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=c*Ov+Is<i.ORDER;function m(_){let k=c>>Is;return _>k}function w(_,k){if(!a.isValidNot0(k))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return k}function x(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(_,k){J6(k);let N=p.signature,F=k==="compact"?N:k==="recovered"?N+1:void 0;return ye(_,F)}class S{r;s;recovery;constructor(k,N,F){if(this.r=w("r",k),this.s=w("s",N),F!=null){if(x(),![0,1,2,3].includes(F))throw new Error("invalid recovery id");this.recovery=F}Object.freeze(this)}static fromBytes(k,N=y.format){E(k,N);let F;if(N==="der"){let{r:Z,s:fe}=In.toSig(ye(k));return new S(Z,fe)}N==="recovered"&&(F=k[0],N="compact",k=k.subarray(1));let P=p.signature/2,$=k.subarray(0,P),H=k.subarray(P,P*2);return new S(a.fromBytes($),a.fromBytes(H),F)}static fromHex(k,N){return this.fromBytes(hc(k),N)}assertRecovery(){let{recovery:k}=this;if(k==null)throw new Error("invalid recovery id: must be present");return k}addRecoveryBit(k){return new S(this.r,this.s,k)}recoverPublicKey(k){let{r:N,s:F}=this,P=this.assertRecovery(),$=P===2||P===3?N+c:N;if(!i.isValid($))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes($),Z=r.fromBytes(xt(Mv((P&1)===0),H)),fe=a.inv($),ue=I(ye(k,void 0,"msgHash")),Ne=a.create(-ue*fe),Oe=a.create(F*fe),Be=r.BASE.multiplyUnsafe(Ne).add(Z.multiplyUnsafe(Oe));if(Be.is0())throw new Error("invalid recovery: point at infinify");return Be.assertValidity(),Be}hasHighS(){return m(this.s)}toBytes(k=y.format){if(J6(k),k==="der")return hc(In.hexFromSig(this));let{r:N,s:F}=this,P=a.toBytes(N),$=a.toBytes(F);return k==="recovered"?(x(),xt(Uint8Array.of(this.assertRecovery()),P,$)):xt(P,$)}toHex(k){return fc(this.toBytes(k))}}Object.freeze(S.prototype),Object.freeze(S);let T=t.bits2int===void 0?function(k){if(k.length>8192)throw new Error("input is too large");let N=$i(k),F=k.length*8-l;return F>0?N>>BigInt(F):N}:t.bits2int,I=t.bits2int_modN===void 0?function(k){return a.create(T(k))}:t.bits2int_modN,C=zu(l);function U(_){return To("num < 2^"+l,_,zn,C),a.toBytes(_)}function j(_,k){return ye(_,void 0,"message"),k?ye(n(_),void 0,"prehashed message"):_}function z(_,k,N){let{lowS:F,prehash:P,extraEntropy:$}=Q6(N,y);_=j(_,P);let H=I(_),Z=a.fromBytes(k);if(!a.isValidNot0(Z))throw new Error("invalid private key");let fe=[U(Z),U(H)];if($!=null&&$!==!1){let Be=$===!0?o(p.secretKey):$;fe.push(ye(Be,void 0,"extraEntropy"))}let ue=xt(...fe),Ne=H;function Oe(Be){let Ie=T(Be);if(!a.isValidNot0(Ie))return;let Je=a.inv(Ie),uo=r.BASE.multiply(Ie).toAffine(),ei=a.create(uo.x);if(ei===zn)return;let wa=a.create(Je*a.create(Ne+ei*Z));if(wa===zn)return;let Ul=(uo.x===ei?0:2)|Number(uo.y&Is),Fl=wa;return F&&m(wa)&&(Fl=a.neg(wa),Ul^=1),new S(ei,Fl,g?void 0:Ul)}return{seed:ue,k2sig:Oe}}function v(_,k,N={}){let{seed:F,k2sig:P}=z(_,k,N);return jE(n.outputLen,a.BYTES,s)(F,P).toBytes(N.format)}function D(_,k,N,F={}){let{lowS:P,prehash:$,format:H}=Q6(F,y);if(N=ye(N,void 0,"publicKey"),k=j(k,$),!Ui(_)){let Z=_ instanceof S?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Z)}E(_,H);try{let Z=S.fromBytes(_,H),fe=r.fromBytes(N);if(P&&Z.hasHighS())return!1;let{r:ue,s:Ne}=Z,Oe=I(k),Be=a.inv(Ne),Ie=a.create(Oe*Be),Je=a.create(ue*Be),uo=r.BASE.multiplyUnsafe(Ie).add(fe.multiplyUnsafe(Je));return uo.is0()?!1:a.create(uo.x)===ue}catch{return!1}}function L(_,k,N={}){let{prehash:F}=Q6(N,y);return k=j(k,F),S.fromBytes(_,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:v,verify:D,recoverPublicKey:L,Signature:S,hash:n})}var ty={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},WM={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var $v=BigInt(2);function GM(r){let e=ty.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Ye(u,t,e)*u%e,f=Ye(d,t,e)*u%e,h=Ye(f,$v,e)*l%e,p=Ye(h,o,e)*h%e,y=Ye(p,s,e)*p%e,g=Ye(y,a,e)*y%e,m=Ye(g,c,e)*g%e,w=Ye(m,a,e)*y%e,x=Ye(w,t,e)*u%e,E=Ye(x,i,e)*p%e,S=Ye(E,n,e)*l%e,T=Ye(S,$v,e);if(!ey.eql(ey.sqr(T),r))throw new Error("Cannot find square root");return T}var ey=mc(ty.p,{sqrt:GM}),jM=Bv(ty,{Fp:ey,endo:WM}),Tn=Fv(jM,Zr);var Kv=32;function Vv(r,e,t){let n=He.digest(e instanceof Uint8Array?e:e.subarray());if(Ec(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Tn.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Ju(String(o))});try{return Tn.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Ju(String(o))}}function Hv(r,e,t,n){let o=He.digest(t instanceof Uint8Array?t:t.subarray());if(Ec(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Tn.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Zu(String(s))});try{return n?.signal?.throwIfAborted(),Tn.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Zu(String(s))}}var od=class{type="secp256k1";raw;_key;constructor(e){this._key=Wv(e),this.raw=qv(this._key)}toMultihash(){return Ze.digest(Lt(this))}toCID(){return K.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}verify(e,t,n){return Hv(this._key,t,e,n)}},sd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=zv(e),this.publicKey=new od(t??Gv(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:te(this.raw,e.raw)}sign(e,t){return Vv(this.raw,e,t)}};function ry(r){return new sd(r)}function ny(r){return new od(r)}async function jv(){let r=YM();return new sd(r)}function qv(r){return Tn.Point.fromBytes(r).toBytes()}function zv(r){try{return Tn.getPublicKey(r,!0),r}catch(e){throw new $l(String(e))}}function Wv(r){try{return Tn.Point.fromBytes(r),r}catch(e){throw new fo(String(e))}}function Gv(r){try{return Tn.getPublicKey(r,!0)}catch(e){throw new $l(String(e))}}function YM(){return Tn.utils.randomSecretKey()}async function rp(r,e){if(r==="Ed25519")return Cv();if(r==="secp256k1")return jv();if(r==="RSA")return X6(XM(e));if(r==="ECDSA")return LE(QM(e));throw new cn}function Et(r,e){let{Type:t,Data:n}=qn.decode(r),o=n??new Uint8Array;switch(t){case Fe.RSA:return G6(o,e);case Fe.Ed25519:return F6(o);case Fe.secp256k1:return ny(o);case Fe.ECDSA:return l6(o);default:throw new cn}}function Yv(r){let{Type:e,Data:t}=qn.decode(r.digest),n=t??new Uint8Array;switch(e){case Fe.Ed25519:return F6(n);case Fe.secp256k1:return ny(n);case Fe.ECDSA:return l6(n);default:throw new cn}}function Lt(r){return qn.encode({Type:Fe[r.type],Data:r.raw})}function Xv(r){let e=td.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Fe.RSA:return W6(t);case Fe.Ed25519:return U6(t);case Fe.secp256k1:return ry(t);case Fe.ECDSA:return TE(t);default:throw new cn}}function Qv(r){if(r.byteLength===Fr)return U6(r);if(r.byteLength===Kv)return ry(r);let e=Jr(r),t=e[2]?.[0];if(t===mE||t===gE||t===yE)return c6(e);if(e.length>8)return Z1(e);throw new A("Could not extract private key from raw bytes")}function Gi(r){return td.encode({Type:Fe[r.type],Data:r.raw})}function XM(r){return r==null?2048:parseInt(r,10)}function QM(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 A("Unsupported curve, should be P-256, P-384 or P-521")}var Jv=Symbol.for("nodejs.util.inspect.custom"),JM=114,id=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()})`}[yh]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return K.createV1(JM,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Jv](){return`PeerId(${this.toString()})`}},ad=class extends id{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},cd=class extends id{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ld=class extends id{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},ZM=2336,ud=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ze.digest(O(this.url))}[Jv](){return`PeerId(${this.url})`}[yh]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return K.createV1(ZM,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=M(e)),e.toString()===this.toString())}};var eU=114,Zv=2336;function Xe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ee(ge.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return vt(K.parse(r));if(e==null)throw new A('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ee(e.decode(r))}return wt(t)}function Wn(r){if(r.type==="Ed25519")return new cd({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ld({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ad({multihash:r.toCID().multihash,publicKey:r});throw new cn}function eS(r){return Wn(r.publicKey)}function wt(r){if(rU(r))return new ad({multihash:r});if(tU(r))try{let e=Yv(r);if(e.type==="Ed25519")return new cd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ld({multihash:r,publicKey:e})}catch{let t=M(r.digest);return new ud(new URL(t))}throw new va("Supplied PeerID Multihash is invalid")}function vt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==eU&&r.code!==Zv)throw new dh("Supplied PeerID CID is invalid");if(r.code===Zv){let e=M(r.multihash.digest);return new ud(new URL(e))}return wt(r.multihash)}function tU(r){return r.code===Ze.code}function rU(r){return r.code===He.code}function nU(r){return r[Symbol.asyncIterator]!=null}function oU(r){if(nU(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Er=oU;function sU(r){return r[Symbol.asyncIterator]!=null}function iU(r,e){let t=0;if(sU(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=ic(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,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 Kt=iU;function aU(r){return r[Symbol.asyncIterator]!=null}function cU(r,e){return aU(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 Ts=cU;var oy="/ipfs/bitswap/1.2.0";var rt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(rt||(rt={}));var sy;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(sy||(sy={}));(function(r){r.codec=()=>et(sy)})(rt||(rt={}));var ji;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),rt.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:me(0),priority:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=rt.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:rt.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(ji||(ji={}));var dd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),ji.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new he('Decode error - repeated field "entries" had too many elements');c.entries.push(ji.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new he('Streaming decode error - repeated field "entries" had too many elements');for(let f of ji.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(dd||(dd={}));var Yi;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:me(0),data:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Yi||(Yi={}));var $r;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})($r||($r={}));var np;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(np||(np={}));(function(r){r.codec=()=>et(np)})($r||($r={}));var Xi;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&np[s.type]!==0&&(i.uint32(16),$r.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:me(0),type:$r.HaveBlock},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=$r.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:$r.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Xi||(Xi={}));var Qi;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),dd.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Yi.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Xi.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=dd.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new he('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Yi.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new he('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Xi.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield*dd.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new he('Streaming decode error - repeated field "blocks" had too many elements');for(let f of Yi.codec().stream(s,s.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 he('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of Xi.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Qi||(Qi={}));function tS(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.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 op=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var lU=4193648,uU=lU+16;function*rS(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Qi.encode(l).byteLength,{added:d,hasMore:f,newSize:h}=iy(o,l.blocks,a,e,u,dU);a+=d,u=h;let p=f;({added:d,hasMore:f,newSize:h}=iy(n,l.blockPresences,i,e,u,fU)),i+=d,u=h;let y=f;if({added:d,hasMore:f,newSize:h}=iy(t,l.wantlist.entries,s,e,u,hU),s+=d,u=h,c=!p&&!y&&!f,c||(l.wantlist.full=!1),yield Qi.encode(l),c)break}}function iy(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=s(l);if(u>uU)throw new op("Cannot send block as after encoding it is over the max message size");let d=o+u;if(d>n){a=!0;break}e.push(l),i++,o=d}return{hasMore:a,added:i,newSize:o}}function dU(r){return ay(3,Yi.encode(r))}function fU(r){return ay(4,Xi.encode(r))}function hU(r){return ay(1,ji.encode(r))}function ay(r,e){let t=we(r),n=we(e.byteLength);return t+n+e.byteLength}function SU(r){if(yr(r))return r;if(ac(r))return vt(r);if(jr(r)||Array.isArray(r))return r;throw new A(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var sp=class extends le{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??[oy],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 Xt({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 Bn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=Mt();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of Pi(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Qi.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}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.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 R("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 R("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Er(Kt(Ts(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 o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=tS(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new A("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new R("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,oy,s);await a.closeRead(s);try{for(let c of rS(i,this.maxOutgoingMessageSize))a.send(Eo.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new R("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 Cr("Network isn't running");return e=SU(e),t?.onProgress?.(new R("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 Ji(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function ip(r){let e=Ee(ge.decode(`z${r}`));return wt(e)}var Jt=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 Ji(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 Ji(this.map.values(),e=>e.key)}values(){return Ji(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Kr=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 Ji(this.set.entries(),e=>{let t=ip(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ip(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ji(this.set.values(),e=>ip(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 cy(){return new Kr}var ap=class{filter;constructor(e,t){this.filter=Nt(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 ly(r,e=.001){return new ap(r,e)}var uy=class extends Jt{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 _o(r){let{name:e,metrics:t}=r,n;return t!=null?n=new uy({name:e,metrics:t}):n=new Jt,n}var Po=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=$e.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=$e.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=$e.encode(e.multihash.bytes);this.blocks.set(n,t)}};function AU(r){let e=new Uint8Array(r.reduce((n,o)=>n+we(o),0)),t=0;for(let n of r)e=Gt(n,e,t),t+=we(n);return e}var nS=AU;function dy(r){return nS([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var cp=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;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}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,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=K.decode(n.cid),s=M(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===rt.WantHave&&(n.wantType==null||n.wantType===rt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??rt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??rt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[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=M(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Po,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await N1(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===rt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:dy(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:$r.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:dy(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:$r.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((s,i)=>s+i.data.byteLength,0)))}};var lp=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;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.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=_o({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}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}}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)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new cp({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var fy=class extends sc{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){let o=vt(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.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,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(ac(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new R("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function oS(r,e){return new fy(r,e)}var up=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 Vr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Hr(r,e,t,n){let o=new Vr(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){py(t,"abort",d),py(r,e,l),py(r,s,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(o)};hy(t,"abort",d),hy(r,e,l),hy(r,s,u)})}function hy(r,e,t){r!=null&&(sS(r)?r.addEventListener(e,t):r.addListener(e,t))}function py(r,e,t){r!=null&&(sS(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function sS(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function IU(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=_r(r);e.push(t),r=r.slice(we(t))}return e}var iS=IU;var dp=class extends le{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=_o({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=gt({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(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=M(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===rt.WantHave&&t.wantType===rt.WantBlock&&(o.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===rt.WantBlock?(await Hr(this,"block",t?.signal,{filter:a=>te(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Hr(this,"presence",t?.signal,{filter:i=>te(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),o.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=qe(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Po;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).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=M(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Po;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Hr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&te(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:rt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Po;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Hr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&te(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=M(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.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 o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=iS(o.prefix),i=s[0],a=s[1],c=s[2],l=s[3],u=c===He.code?He:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(o.data,{truncate:l});d.then!=null&&(d=await d);let f=K.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:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:o.data}});let h=M(f.multihash.bytes,"base64"),p=this.wants.get(h);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=K.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===$r.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Po(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var fp=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 up(e),this.network=new sp(e,t),this.peerWantLists=new lp({...e,network:this.network},t),this.wantList=new dp({...e,network:this.network},t)}createSession(e={}){return oS({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=de([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new R("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.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(),await this.network.stop()}};var hp=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new fp(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(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!yr(o.detail))return;t.onProgress(new R("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new R("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new R("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new R("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function aS(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new hp(n,e);await ht(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}async function*fd(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 pp=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Ic(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),Ca(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new pp("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Zi=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},en=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var mp={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},gp=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 mt({concurrency:t.concurrentRequests??mp.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??mp.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??mp.cacheName,this.cacheTTL=t.cacheTTL??mp.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),o=de([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;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:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new Zi("Request does not conform to schema or semantic constraints"):new en(`Unexpected status code: ${l.status}`)}let u=l.headers.get("Content-Type");if(u==null)throw new en("No Content-Type header received");if(l.body==null){if(u!=="application/x-ndjson")throw new en("Routing response had no body");return}if(u.startsWith("application/json")){let f=(await l.json()).Providers??[];for(let h of f){let p=this.#e(h);p!=null&&(a++,yield p)}}else if(u.includes("application/x-ndjson"))for await(let d of Ic(fd(l.body))){let f=this.#e(d);f!=null&&(a++,yield f)}else throw new en(`Unsupported Content-Type: ${u}`)}finally{o.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),o=de([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;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:o});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 en("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let d=(await c.json()).Peers??[];for(let f of d){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Ic(fd(c.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(K.asCID(e)===e||e instanceof K)n=e.toV1().toString();else throw new A("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=de([this.shutDownController.signal,o,t.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;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:s});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 en("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await l.json()).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else for await(let d of Ic(fd(l.body))){let f=this.#e(d);f!=null&&(yield f)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.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),o=de([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let c=await this.#r(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new Te("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 en(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new Te("No matching records found");if(c.body==null)throw new en("GET ipns response had no body");let u=await c.arrayBuffer();return new Uint8Array(u,0,u.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=de([this.shutDownController.signal,o,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 i.promise;let l=await this.#r(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ee(t),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new en("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(G)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:K.createV1(114,TU(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),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 this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}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 TU(r){let e=ge.baseDecode(r);return Ee(e)}function CU(r){return r[Symbol.asyncIterator]!=null}function kU(r){if(CU(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var yp=kU;var wp=O("/ipns/");function cS(r){return te(r.subarray(0,wp.byteLength),wp)}var bp=class{client;constructor(e){this.client=e}get[ri](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async*findProviders(e,t={}){try{yield*Kt(this.client.getProviders(e,t),n=>({id:vt(n.ID),multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Te)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!cS(e))return;let o=Ee(e.slice(wp.length)),s=K.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!cS(e))throw new Te("Not found");let n=Ee(e.slice(wp.length)),o=K.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new Te("Not found"):s}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},xp=class{client;constructor(e){this.client=e}get[ai](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async findPeer(e,t={}){let n=await yp(this.client.getPeers(e.toCID(),t));if(n!=null)return{id:vt(n.ID),multiaddrs:n.Addrs??[]};throw new Te("Not found")}async*getClosestPeers(e,t={}){let n;try{n=K.decode(e)}catch{try{n=K.createV1(114,ze.decode(e))}catch{n=K.createV1(po,Ze.digest(e))}}for await(let o of this.client.getClosestPeers(n,t))yield{id:vt(o.ID),multiaddrs:o.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};function Ep(r){return e=>new gp(e,r)}function lS(r){return e=>new bp(Ep(r)(e))}function uS(r){return e=>new xp(Ep(r)(e))}var vp=O("/ipns/");function dS(r){return te(r.subarray(0,vp.byteLength),vp)}var Sp=class{name="delegated-http-router";client;constructor(e,t){this.client=Ep(t)(e)}async provide(e,t){}async cancelReprovide(e,t){}async*findProviders(e,t){yield*Kt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(e,t,n){if(!dS(e))return;let o=Ee(e.slice(vp.length)),s=K.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!dS(e))throw new Te("Not found");let n=Ee(e.slice(vp.length)),o=K.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new Te("Not found"):s}}async findPeer(e,t){let n=await yp(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Te("Not found")}async*getClosestPeers(e,t){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function hd(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function fS(r){return e=>new Sp(e,hd(r))}var hS="[a-fA-F\\d:]",Cs=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${hS})|(?<=${hS})(?=\\s|$))`:"",Cn="(?: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}",bt="[a-fA-F\\d]{1,4}",Ap=`
|
|
13
13
|
(?:
|
|
14
14
|
(?:${bt}:){7}(?:${bt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
15
15
|
(?:${bt}:){6}(?:${Cn}|:${bt}|:)| // 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
|
|
@@ -20,7 +20,7 @@ ${e}[Error list was empty]`,t.trim()}return aE(r,e)}je.formatters.e=r=>r==null?"
|
|
|
20
20
|
(?:${bt}:){1}(?:(?::${bt}){0,4}:${Cn}|(?::${bt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
21
21
|
(?::(?:(?::${bt}){0,5}:${Cn}|(?::${bt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
22
22
|
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
23
|
-
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),_U=new RegExp(`(?:^${Cn}$)|(?:^${Ap}$)`),PU=new RegExp(`^${Cn}$`),LU=new RegExp(`^${Ap}$`),my=r=>r&&r.exact?_U:new RegExp(`(?:${Cs(r)}${Cn}${Cs(r)})|(?:${Cs(r)}${Ap}${Cs(r)})`,"g");my.v4=r=>r&&r.exact?PU:new RegExp(`${Cs(r)}${Cn}${Cs(r)}`,"g");my.v6=r=>r&&r.exact?LU:new RegExp(`${Cs(r)}${Ap}${Cs(r)}`,"g");var gy=my;function yy(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function pS(){return!1}var{toString:DU}=Object.prototype;function wy(r){return DU.call(r)==="[object RegExp]"}var mS={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function by(r,e={}){if(!wy(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(mS).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?mS[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function xy(r,e,{timeout:t}={}){try{return yy(()=>by(r).test(e),{timeout:t})()}catch(n){if(pS(n))return!1;throw n}}var RU=15,NU=45,gS={timeout:400};function Ey(r){return r.length>NU?!1:xy(gy.v6({exact:!0}),r,gS)}function yS(r){return r.length>RU?!1:xy(gy.v4({exact:!0}),r,gS)}var wS={http:"80",https:"443",ws:"80",wss:"443"},OU=["http","https","ws","wss"];function Tc(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=BU(r),a=[MU(o,t),UU(s,n),FU(n)];i!=null&&a.push($U(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return G(c)}function BU(r){let[e]=r.split(":");OU.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=KU(e);c!=null&&(o=c),c==null&&t==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:e,hostname:n,port:o,path:a}}function MU(r,e){if(!(r==null||r==="")){if(yS(r))return["ip4",r];if(Ey(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Ey(t))return["ip6",t]}return[e,r]}}function UU(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function FU(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function $U(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function KU(r){if(!(r==null||r===""||wS[r]==null))return wS[r]}var VU=
|
|
23
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),_U=new RegExp(`(?:^${Cn}$)|(?:^${Ap}$)`),PU=new RegExp(`^${Cn}$`),LU=new RegExp(`^${Ap}$`),my=r=>r&&r.exact?_U:new RegExp(`(?:${Cs(r)}${Cn}${Cs(r)})|(?:${Cs(r)}${Ap}${Cs(r)})`,"g");my.v4=r=>r&&r.exact?PU:new RegExp(`${Cs(r)}${Cn}${Cs(r)}`,"g");my.v6=r=>r&&r.exact?LU:new RegExp(`${Cs(r)}${Ap}${Cs(r)}`,"g");var gy=my;function yy(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function pS(){return!1}var{toString:DU}=Object.prototype;function wy(r){return DU.call(r)==="[object RegExp]"}var mS={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function by(r,e={}){if(!wy(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(mS).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?mS[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function xy(r,e,{timeout:t}={}){try{return yy(()=>by(r).test(e),{timeout:t})()}catch(n){if(pS(n))return!1;throw n}}var RU=15,NU=45,gS={timeout:400};function Ey(r){return r.length>NU?!1:xy(gy.v6({exact:!0}),r,gS)}function yS(r){return r.length>RU?!1:xy(gy.v4({exact:!0}),r,gS)}var wS={http:"80",https:"443",ws:"80",wss:"443"},OU=["http","https","ws","wss"];function Tc(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=BU(r),a=[MU(o,t),UU(s,n),FU(n)];i!=null&&a.push($U(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return G(c)}function BU(r){let[e]=r.split(":");OU.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=KU(e);c!=null&&(o=c),c==null&&t==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:e,hostname:n,port:o,path:a}}function MU(r,e){if(!(r==null||r==="")){if(yS(r))return["ip4",r];if(Ey(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Ey(t))return["ip6",t]}return[e,r]}}function UU(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function FU(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function $U(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function KU(r){if(!(r==null||r===""||wS[r]==null))return wS[r]}var VU=2336;function HU(r){return r=r.toString(),{id:K.createV1(VU,Ze.digest(O(r))),multiaddrs:[Tc(r)]}}function qU(r){return new URL(M(r.id.multihash.digest))}var vy=class{name="fallback-router";gateways;shuffle;constructor(e){this.gateways=e.gateways.map(t=>HU(t))??[],this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,id:n.id,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(e=>qU(e)).join(", ")}])`}};function bS(r){return new vy(r)}var zU=[6,53,56,54,55];function xS(r){return SS("sni",r)?.value}function ES(r){let e=SS("tcp",r)?.value;return e==null?"":`:${e}`}function SS(r,e){return e.find(t=>t.name===r)}function vS(r){return r.some(({code:e})=>e===448)}function kn(r,e){let t=AS[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var AS={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${kn(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${kn(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${kn(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${kn(t,e)}`},http:(r,e)=>{let t=vS(e),n=xS(e),o=ES(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=kn(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=kn(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return kn(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return kn(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=kn(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=vS(e),n=xS(e),o=ES(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=kn(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=kn(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function ks(r,e){let n=G(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=AS[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&zU.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}function Sy(r,e,t){return r.filter(n=>{let o=H9.exactMatch(n),s=V9.exactMatch(n);if(!o&&!s)return!1;if(o||e&&s)return t||Xh.matches(n)?!0:it(n)===!1;if(!e&&t){let{host:i}=ce(n);if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*Ip(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=Sy(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(ks(a[0]));yield new Cc(c,{logger:t,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function IS(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{o?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new Y;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var WU=2336,Cc=class{url;peer;#e=0;#t=0;#r=0;#a=0;#c=new Map;log;transformRequestInit;routing;constructor(e,{logger:t,transformRequestInit:n,routing:o}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=K.createV1(WU,Ze.digest(O(this.url.toString())))}#m(e){let t=e.multihash.bytes;return $e.encode(t)}async getRawBlock(e,t={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${e.toString()}`;let o=t.maxSize??TS;if(n.search="?format=raw",t.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#m(e),i=new AbortController,a=()=>{i.abort()};t.signal?.addEventListener("abort",a);try{let c=this.#c.get(s);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l,d=new Headers(u.headers);this.log(`sending request
|
|
24
24
|
%s %s HTTP/1.1
|
|
25
25
|
%s
|
|
26
26
|
`,u.method??"GET",n,[...d.entries()].map(([f,h])=>`${f}: ${h}`).join(`
|
|
@@ -28,7 +28,7 @@ ${e}[Error list was empty]`,t.trim()}return aE(r,e)}je.formatters.e=r=>r==null?"
|
|
|
28
28
|
HTTP/1.1 %d %s
|
|
29
29
|
%s
|
|
30
30
|
`,f.status,f.statusText,[...f.headers.entries()].map(([p,y])=>`${p}: ${y}`).join(`
|
|
31
|
-
`)),!f.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${f.status} ${f.statusText}`);t.onProgress?.(new R("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Tc(n.toString()),cid:e})),t.onProgress?.(new R("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:e}));let h=await IS(f,o,{signal:i.signal,log:this.log});return t.onProgress?.(new R("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:e})),this.#a++,h}),this.#c.set(s,c)}return await c}catch(c){throw t.signal?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t.signal?.removeEventListener("abort",a),this.#c.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#c.size}}toString(){return`TrustlessGateway(${this.url})`}};var Ay=class extends sc{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Tp,this.allowLocal=t.allowLocal??Cp,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url),n?.onProgress?.(new R("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}));let o;try{o=await t.getRawBlock(e,n),this.log.trace("got block for %c from %s",e,t.url)}finally{n?.onProgress?.(new R("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}))}return await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*Ip(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(n?.signal?.throwIfAborted(),ac(e))return;let o=Sy(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=ks(o[0]);return new Cc(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new R("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function CS(r,e){return new Ay(r,e)}var kp=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Tp,this.allowLocal=t.allowLocal??Cp,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of Ip(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return CS({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Tp=!1,Cp=!1,TS=2097152;function kS(r={}){return e=>new kp(e,r)}function _S(r,e){return e?.routers??[bS(),fS({url:"https://delegated-ipfs.dev"})].forEach(t=>{r.addRouter(t)}),e?.blockBrokers??[kS()].forEach(t=>{r.addBlockBroker(t)}),r}async function PS(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new A("Private network is enforced, but no protector was provided");return r}var pd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:me(0),payloadType:me(0),payload:me(0),signature:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(pd||(pd={}));var _p=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var qr=class r{static createFromProtobuf=e=>{let t=pd.decode(e),n=Et(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=LS(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new _p("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=pd.encode({publicKey:Lt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:te(this.marshal(),e.marshal())}async validate(e,t){let n=LS(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},LS=(r,e,t)=>{let n=O(r),o=Gt(n.byteLength),s=Gt(e.length),i=Gt(t.length);return new Y(o,n,s,e,i,t)};var DS="libp2p-peer-record",RS=Uint8Array.from([3,1]);var md;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=ae((d,f,h={})=>{h.lengthDelimited!==!1&&f.fork(),d.multiaddr!=null&&d.multiaddr.byteLength>0&&(f.uint32(10),f.bytes(d.multiaddr)),h.lengthDelimited!==!1&&f.ldelim()},(d,f,h={})=>{let p={multiaddr:me(0)},y=f==null?d.len:d.pos+f;for(;d.pos<y;){let g=d.uint32();g>>>3===1?p.multiaddr=d.bytes():d.skipType(g&7)}return p},function*(d,f,h,p={}){let y=f==null?d.len:d.pos+f;for(;d.pos<y;){let g=d.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:d.bytes()}:d.skipType(g&7)}})),a);function c(d){return se(d,i.codec())}i.encode=c;function l(d,f){return oe(d,i.codec(),f)}i.decode=l;function u(d,f){return ie(d,i.codec(),f)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ae((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:me(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new he('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(d&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},d=a==null?i.len:i.pos+a;for(;i.pos<d;){let f=i.uint32();switch(f>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new he('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(f&7);break}}}})),t);function n(i){return se(i,r.codec())}r.encode=n;function o(i,a){return oe(i,r.codec(),a)}r.decode=o;function s(i,a){return ie(i,r.codec(),a)}r.stream=s})(md||(md={}));function NS(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var dr=class r{static createFromProtobuf=e=>{let t=md.decode(e),n=wt(Ee(t.peerId)),o=(t.addresses??[]).map(i=>G(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=DS;static CODEC=RS;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=md.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!NS(this.multiaddrs,e.multiaddrs))}};function jU(r){return r[Symbol.asyncIterator]!=null}function YU(r){if(jU(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Lo=YU;var Pp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Lp=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Vr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function XU(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Dp=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=XU(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Vr),this.cleanup())}async join(e={}){let t=new Lp(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ue(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Iy(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var gd=class extends le{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Iy(this.emitEmpty.bind(this),1),this.emitIdle=Iy(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Pp;let n=new Dp(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Vr)}),this.clear()}async onEmpty(e){this.size!==0&&await Hr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Hr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Hr(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Mt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Vr("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Rp="lock:worker:request-read",Np="lock:worker:abort-read-request",Op="lock:worker:release-read",Bp="lock:master:grant-read",Mp="lock:master:error-read",Up="lock:worker:request-write",Fp="lock:worker:abort-write-request",$p="lock:worker:release-write",Kp="lock:master:grant-write",Vp="lock:master:error-write",Hp="lock:worker:finalize",qp="mortice",OS={singleProcess:!1};var Ty=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let f=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Hp&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var BS=(r=10)=>Math.random().toString().substring(2,r+2);var zp=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(qp)}readLock(e){return this.sendRequest(Rp,Np,Bp,Mp,Op,e)}writeLock(e){return this.sendRequest(Up,Fp,Kp,Vp,$p,e)}finalize(){this.channel.postMessage({type:Hp,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=BS();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=f=>{if(f.data?.identifier===a&&(f.data?.type===n&&(this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),f.data.type===o)){this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u);let h=new Error;f.data.error!=null&&(h.message=f.data.error.message,h.name=f.data.error.name,h.stack=f.data.error.stack),l(h)}};this.channel.addEventListener("message",d)})}};var MS=r=>{if(r=Object.assign({},OS,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(qp),n=new le;return t.addEventListener("message",Ty(n,t,"requestReadLock","abortReadLockRequest",Rp,Np,Mp,Op,Bp)),t.addEventListener("message",Ty(n,t,"requestWriteLock","abortWriteLockRequest",Up,Fp,Vp,$p,Kp)),n}return new zp(r.name)};var ea=new Map,yd;function US(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function QU(r){if(yd==null&&(yd=MS(r),!US(yd))){let e=yd;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=ea.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=ea.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=ea.get(n);o?.finalize()})}return yd}async function Cy(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Vr)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var FS=(r,e)=>{let t=ea.get(r);if(t!=null)return t;let n=QU(e);if(US(n))return t=n,ea.set(r,t),t;let o=new gd({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Cy(s,i);s=new gd({concurrency:e.concurrency,autoStart:!1});let a=s,c=Cy(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Cy(o,i)},finalize:()=>{ea.delete(r)},queue:o},ea.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var JU={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function wd(r){let e=Object.assign({},JU,r);return FS(e.name,e)}var Do;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&f.value.byteLength>0&&(h.uint32(18),h.bytes(f.value)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:"",value:me(0)},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.key=f.string();break}case 2:{y.value=f.bytes();break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield{field:`${p}.value`,value:f.bytes()};break}default:{f.skipType(m&7);break}}}})),c);function l(f){return se(f,a.codec())}a.encode=l;function u(f,h){return oe(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&(h.uint32(18),xd.codec().encode(f.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:""},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.key=f.string();break}case 2:{y.value=xd.codec().decode(f,f.uint32(),{limits:p.limits?.value});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield*xd.codec().stream(f,f.uint32(),`${p}.value`,{limits:y.limits?.value});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return se(f,a.codec())}a.encode=l;function u(f,h){return oe(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),bd.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,d]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:d},c);if(a.tags!=null&&a.tags.size>0)for(let[u,d]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:d},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new he('Decode error - repeated field "addresses" had too many elements');u.addresses.push(bd.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new he('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new ru('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new ru('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={addresses:0,protocols:0,metadata:0,tags:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&d.addresses===u.limits.addresses)throw new he('Streaming decode error - repeated field "addresses" had too many elements');for(let p of bd.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:d.addresses};d.addresses++;break}case 2:{if(u.limits?.protocols!=null&&d.protocols===u.limits.protocols)throw new he('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:d.protocols,value:a.string()},d.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&d.metadata===u.limits.metadata)throw new he('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),d.metadata++;break}case 7:{if(u.limits?.tags!=null&&d.tags===u.limits.tags)throw new he('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),d.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Do||(Do={}));var bd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(bd||(bd={}));var xd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(xd||(xd={}));function ZU(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Et(e.publicKey,t);return Wn(n)}function $S(r,e,t){let n=Do.decode(e);return kc(r,n,t)}function kc(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:ZU(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:G(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function KS(r,e){return eF(r.addresses,e.addresses)&&tF(r.protocols,e.protocols)&&rF(r.publicKey,e.publicKey)&&nF(r.peerRecordEnvelope,e.peerRecordEnvelope)&&oF(r.metadata,e.metadata)&&sF(r.tags,e.tags)}function eF(r,e){return HS(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!te(t.multiaddr,n.multiaddr)))}function tF(r,e){return HS(r,e,(t,n)=>t===n)}function rF(r,e){return VS(r,e)}function nF(r,e){return VS(r,e)}function oF(r,e){return qS(r,e,(t,n)=>te(t,n))}function sF(r,e){return qS(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function VS(r,e){return r==null&&e==null?!0:r!=null&&e!=null?te(r,e):!1}function HS(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function qS(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Ro="/",zS=new TextEncoder().encode(Ro),Wp=zS[0],Me=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=O(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Wp)throw new Error("Invalid key")}toString(e="utf8"){return M(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ro))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=zS),this._buf[0]!==Wp){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Wp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Wp;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ro).slice(1)}type(){return iF(this.baseNamespace())}name(){return aF(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ro)||(e+=Ro),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ro):new r(e.slice(0,-1).join(Ro))}child(e){return this.toString()===Ro?e:e.toString()===Ro?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...cF(e.map(t=>t.namespaces()))])}};function iF(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function aF(r){let e=r.split(":");return e[e.length-1]}function cF(r){return[].concat(...r)}var ky="/peers/";function Ed(r){if(!yr(r)||r.type==null)throw new A("Invalid PeerId");let e=r.toCID().toString();return new Me(`${ky}${e}`)}async function WS(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=G(i.multiaddr)),!jr(i.multiaddr))throw new A("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(G(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function jp(r,e,t,n){if(e==null)throw new A("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new A("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new A("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Gp(f,{validate:GS})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Gp(f,{validate:jS,map:YS})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=Gp([...a.entries()],{validate:GS})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,y]of f)y==null?h.delete(p):h.set(p,y);c=Gp([...h.entries()],{validate:jS,map:YS})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Lt(o.id.publicKey):e.publicKey!=null?u=Lt(e.publicKey):r.publicKey!=null&&(u=Lt(r.publicKey));let d={addresses:await WS(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=n.existingPeer?.peerPB.addresses?.find(h=>te(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function Gp(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function GS(r,e){if(typeof r!="string")throw new A("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new A("Metadata value must be a Uint8Array")}function jS(r,e){if(typeof r!="string")throw new A("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new A("Tag value must be an integer");if(e.value<0||e.value>100)throw new A("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new A("Tag ttl must be an integer");if(e.ttl<0)throw new A("Tag ttl must be between greater than 0")}}function YS(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function XS(r){let e=r.toString().split("/")[2],t=K.parse(e,pt);return vt(t)}function _y(r,e,t){let n=XS(r);return $S(n,e,t)}function lF(r,e){return{prefix:ky,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(_y(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(_y(n.key,n.value,e),_y(o.key,o.value,e)))}}var Yp=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=_o({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:wd({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Ed(e),t)}async load(e,t){let n=Ed(e),o=await this.datastore.get(n,t),s=Do.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Te;return kc(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await jp(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await jp(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await jp(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(lF(e??{},this.maxAddressAge),e)){let o=XS(t);if(o.equals(this.peerId))continue;let s=Do.decode(n);if(this.#r(o,s)){await this.datastore.delete(t,e);continue}yield kc(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Ed(e),o=await this.datastore.get(n,t),s=Do.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Te;return{peerPB:s,peer:kc(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Do.encode(t);return await this.datastore.put(Ed(e),s,o),{peer:kc(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!KS(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Py=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Yp(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Lo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=yr(t)?t:yr(t?.expectedPeer)?t.expectedPeer:void 0,s=yr(t)||t===void 0?n:t,i=await qr.openAndCertify(e,dr.DOMAIN,s),a=vt(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=dr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=qr.createFromProtobuf(l.peerRecordEnvelope),d=dr.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function QS(r,e={}){return new Py(r,e)}var tn=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function uF(r){return r[Symbol.asyncIterator]!=null}function dF(r,e){return uF(r)?(async function*(){yield*(await Lo(r)).sort(e)})():(function*(){yield*Lo(r).sort(e)})()}var Xp=dF;var No=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Er(this.putMany(e,n)),e=[],await Er(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Br(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xp(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Br(n,()=>o++>=s)}return e.limit!=null&&(n=Ts(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Br(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xp(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Br(n,()=>s++>=o)}return e.limit!=null&&(n=Ts(n,e.limit)),n}};var ta=class extends No{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new tn;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Me(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Me(n),t?.signal?.throwIfAborted()}};var JS=864e13;var Qp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=gt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=ce(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Ma(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?JS-Date.now():0,lastVerified:o?JS-Date.now():void 0})})}remove(e){let t=ce(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Ot(o))continue;let s=ce(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),G(n)}confirm(e,t){let n=ce(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=ce(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Jp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=gt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=ce(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:hn(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=ce(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Ot(n))continue;let o=ce(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,G(i)):e}confirm(e,t){if(!Ot(e))return!1;let n=ce(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!Ot(e))return!1;let n=ce(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var fF={maxObservedAddresses:10},Zp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??fF.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(it(e)||h9(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:G(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var hF={maxObservedAddresses:10},e0=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??hF.maxObservedAddresses}get(e,t){if(it(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Ot(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!Ot(e))return e.toString();let t=ce(e);return`${t.host}-${t.port}-${t.protocol}`}};var ZS=6e4,eA={maxObservedAddresses:10,addressVerificationTTL:ZS*10,addressVerificationRetry:ZS*5},pF=r=>r;function Ly(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&Xe(t).equals(e)&&(r=r.decapsulate(G(`/p2p/${e.toString()}`))),r}var t0=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Zp(e,t),this.dnsMappings=new Qp(e,t),this.ipMappings=new Jp(e,t),this.transportAddresses=new e0(e,t),this.announceFilter=t.announceFilter??pF,this.observedAddressFilter=Nt(1024),this.addressVerificationTTL=t.addressVerificationTTL??eA.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??eA.addressVerificationRetry,this._updatePeerStoreAddresses=bo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>G(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>G(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>G(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=ce(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Ly(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Ly(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Ly(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=G(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(G(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${hn(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(G(`/ip${hn(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Ot(e))return!1;let t=ce(e);if(t.type!=="ip4"||Ma(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>wo.exactMatch(s)||Ai.exactMatch(s),s=>Si.exactMatch(s),s=>M9.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>ce(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!pu(l)).pop();if(a==null)continue;let c=ce(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var tA;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(tA||(tA={}));var r0=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},n0=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},_c=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},vd=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},o0=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},s0=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},i0=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Sd=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},a0=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},c0=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},l0=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},u0=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},d0=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},_s=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},ra=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},f0=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},h0=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Dy=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=tc())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>wh(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},mF=["metrics","connectionProtector","dns"],gF=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function rA(r={}){let e=new Dy(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!gF.includes(o)){let i=e.components[o];if(i==null&&!mF.includes(o))throw new r0(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function nA(r){let e={};for(let t of Object.values(r.components))for(let n of yF(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of wF(t))if(e[n]!==!0)throw new n0(`Service "${bF(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function yF(r){return Array.isArray(r?.[xe])?r[xe]:[]}function wF(r){return Array.isArray(r?.[kr])?r[kr]:[]}function bF(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function oA(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>wo.matches(e)?!0:it(e)),r}var xF=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 EF(r,e,t){let n,o=new Promise((s,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}=xF(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=cr(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ad(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=EF(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function p0(r){if(yr(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:Xe(n),e.forEach(o=>{if(!jr(o))throw new On("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new A("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Xe(s);if(t?.equals(i)!==!0)throw new A("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!D9.exactMatch(n)),{peerId:t,multiaddrs:e}}var vF=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function sA(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??vF;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Id(r){let e=ce(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new A(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new A(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new bi(e.host,t)}function Ry(r){return!_t.exactMatch(r)}function m0(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Ry(s)))return n}var g0=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Id(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Jt;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(Ot(c.remoteAddr)){let d=ce(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await sA(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var iA="last-dial-failure",aA="last-dial-success";var cA=100,y0=50;function SF(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function lA(r){return r.sort((e,t)=>z9(e.multiaddr,t.multiaddr)||W9(e.multiaddr,t.multiaddr)||G9(e.multiaddr,t.multiaddr)||SF(e,t)||q9(e.multiaddr,t.multiaddr))}var w0=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},b0=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var Oy=ti(dA(),1);function By(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var TF=100,Pc=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#r();let a=By(this.#e,i,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>TF&&this.#t>this.#e.length/2&&this.#r(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#r(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Cd=class extends Oy.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#u;#C=0;#x=0;#d;#f;#l;#i=[];#s=0;#n;#k;#o=0;#y;#h;#R=1n;#w=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Pc,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#u=e.interval,this.#l=e.strict,this.#n=new e.queueClass,this.#k=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#h=e.autoStart===!1,this.#K()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#u)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#N(e){this.#l?this.#i.push(e):this.#r++}#O(){this.#l?this.#i.length>this.#s&&this.#i.pop():this.#r>0&&this.#r--}#S(){return this.#i.length-this.#s}get#B(){return this.#t?!0:this.#l?this.#S()<this.#a:this.#r<this.#a}get#M(){return this.#o<this.#y}#U(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#f=void 0,this.#L(),this.#P()}#$(e){if(this.#l){if(this.#v(e),this.#S()>=this.#a){let n=this.#i[this.#s],o=this.#u-(e-n);return this.#A(o),!0}return!1}if(this.#d===void 0){let t=this.#C-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#u)return this.#A(this.#u-n),!0}this.#r=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#F()},e))}#I(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}#_(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#b(){if(this.#n.size===0){if(this.#I(),this.emit("empty"),this.#o===0){if(this.#_(),this.#l&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#h){let t=Date.now(),n=!this.#$(t);if(this.#B&&this.#M){let o=this.#n.dequeue();this.#t||(this.#N(t),this.#g()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#t||this.#d!==void 0||this.#l||(this.#d=setInterval(()=>{this.#L()},this.#u),this.#C=Date.now()+this.#u)}#L(){this.#l||(this.#r===0&&this.#o===0&&this.#d&&this.#I(),this.#r=this.#e?this.#o:0),this.#T(),this.#g()}#T(){for(;this.#b(););}get concurrency(){return this.#y}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#T()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#n.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#w.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(f){throw this.#V(),this.#w.delete(s),f}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=cr(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:f}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(f.reason)},f.addEventListener("abort",l,{once:!0})})])}let d=await u;n(d),this.emit("completed",d)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#w.delete(s),queueMicrotask(()=>{this.#U()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof Pc){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),o(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#E.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#T(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#n=new this.#k,this.#I(),this.#D(),this.emit("empty"),this.#o===0&&(this.#_(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#h}#K(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#D()}))}#V(){this.#t||(this.#O(),this.#g())}#D(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#l){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function E0(r){let e=[zr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var My=60;function v0(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:zr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:zr[e.type],TTL:e.TTL??e.ttl??My,data:e.data instanceof Uint8Array?M(e.data):e.data}))}}var CF=4;function Uy(r,e={}){let t=new Cd({concurrency:e.queryConcurrency??CF});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),E0(o.types).forEach(c=>{i.append("type",zr[c])}),o.onProgress?.(new R("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=v0(await c.json());return o.onProgress?.(new R("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function fA(){return[Uy("https://cloudflare-dns.com/dns-query"),Uy("https://dns.google/resolve")]}var mA=ti(pA(),1);var Fy=class{lru;constructor(e){this.lru=(0,mA.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return v0({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:zr[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??My)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function gA(r){return new Fy(r)}var kF=1e3,_F=()=>Math.random()>.5?-1:1,S0=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=gA(e.cacheSize??kF),this.logger=e.logger,this.sorter=e.sorter??_F,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=fA())}async query(e,t={}){let n=E0(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new R("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});if(l.Answer.length===0)throw new b0("Query result had no answers");for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new R("dns:error",l))}}throw new w0(a,`DNS lookup of ${e} ${n} failed`)}};var zr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(zr||(zr={}));function A0(r={}){return new S0(r)}var $y=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[zr.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(G(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=A0()),this.dns)}},kd=new $y;async function Ky(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new h0("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Ky(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Lc={maxParallelDials:y0,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:kd}},I0=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??Lc.addressDialTimeout,this.connections=t.connections??new Jt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Lc.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new _1({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==nr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=p0(e);if(n!=null&&t.force!==!0){let i=m0(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new R("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new R("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Zo("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new R("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new R("dial-queue:start-dial"));let a=de([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Wy,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],d=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let f=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let h of f){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new R("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Zo("Peer had more than maxPeerAddrsToDial");a++;let p=de([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let y=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(y.remotePeer,{multiaddrs:[y.remoteAddr],metadata:{[aA]:O(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return y}catch(y){if(this.log.error("dial failed to %a - %e",h.multiaddr,y),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[iA]:O(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new Bn(y.message);l.push(y)}finally{p.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(d=>({multiaddr:G(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Zo("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Sd("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);o.push(...d.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let s=(await Promise.all(o.map(async d=>{let f=await Ky(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;s=s.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}let i=s.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let f=d.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let d of i){let f=d.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||d.isCertified||!1;continue}a.set(f,d)}let c=[...a.values()];if(c.length===0)throw new l0(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?lA(l):l.sort(this.addressSorter);if(u.length===0)throw new Sd(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!_t.matches(o.multiaddr))!=null:!0}catch{}return!1}};var PF=Object.prototype.toString,LF=r=>PF.call(r)==="[object Error]",DF=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Gy(r){if(!(r&&LF(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:DF.has(t)}function RF(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function T0(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function jy(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var Yy=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function NF(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function C0(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function OF(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function BF({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof Yy)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=NF(t,o);if(C0(n,a)<=0){let m=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(m),s}let u=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),d=await o.shouldConsumeRetry(u),f=d&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:f});if(await o.onFailedAttempt(h),C0(n,a)<=0||C0(n,a)<=0||i<=0||s instanceof TypeError&&!Gy(s)||!await o.shouldRetry(h))throw s;let y=C0(n,a);if(y<=0)throw s;if(!d)return o.signal?.throwIfAborted(),!1;let g=Math.min(f,y);return o.signal?.throwIfAborted(),await OF(g,o),o.signal?.throwIfAborted(),!0}async function Xy(r,e={}){if(e={...e},RF(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,jy("onFailedAttempt",e.onFailedAttempt),jy("shouldRetry",e.shouldRetry),jy("shouldConsumeRetry",e.shouldConsumeRetry),T0("factor",e.factor,{min:0,allowInfinity:!1}),T0("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),T0("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),T0("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await BF({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var k0=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Xt({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);yA(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Xy(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(ci)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>yA(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function yA(r){for(let e of r.tags.keys())if(e.startsWith(ci))return!0;return!1}var Wy=50,Qy={maxConnections:cA,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},_0=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Qy.maxConnections,this.maxConnections<1)throw new A("Connection Manager maxConnections must be greater than 0");this.connections=new Jt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Id(G(n))),this.deny=(t.deny??[]).map(n=>Id(G(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Qy.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new nc({points:t.inboundConnectionThreshold??Qy.inboundConnectionThreshold,duration:1}),this.connectionPruner=new g0({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>G(n))}),this.dialQueue=new I0(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??y0,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:kd},connections:this.connections}),this.reconnectQueue=new k0({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await ht(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Ct(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([Ad(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new A("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Cr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new R("connection:open",e));let{peerId:n,multiaddrs:o}=p0(e);if(this.peerId.equals(n))throw new Ea("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=m0(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new R("dial-queue:already-connected")),t.onProgress?.(new R("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Wy});if(s.status!=="open")throw new ni("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new On("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new R("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([Ad(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Ot(e.remoteAddr)){let s=ce(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Ot(e.remoteAddr)){let s=ce(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Ot(e.remoteAddr)){let o=ce(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>G(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var FF=1e4,$F="1.0.0",KF="ping",VF="ipfs",wA=32,HF=!0,P0=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??VF}/${KF}/${$F}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??FF,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??HF,this.timeout=new yn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xe]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=a1(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(wA)),{signal:n}),s.read({bytes:wA,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var L0=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new _c("No content routers available");let n=this,o=new Kr;for await(let s of lr(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new _c("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new _c("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Cr;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Cr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var D0=globalThis.CustomEvent??Event;async function*Oo(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=qe(),a=qe(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=qe(),await i.promise),u)break;let y={done:!1};s.push(y),p().then(g=>{y.done=!0,y.ok=!0,y.value=g,o.dispatchEvent(new D0("task-complete"))},g=>{y.done=!0,y.err=g,o.dispatchEvent(new D0("task-complete"))})}c=!0,o.dispatchEvent(new D0("task-complete"))}catch(p){l=p,o.dispatchEvent(new D0("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(p=>p.done)}function*f(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;d();)for(let p=0;p<s.length;p++)if(s[p].done){let y=s[p];if(s.splice(p,1),p--,y.ok)yield y.value;else throw u=!0,i.resolve(),y.err;i.resolve()}}for(;;){if(d()||(a=qe(),await a.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var R0=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:M(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new vd("No peer routers available");if(e.toString()===this.peerId.toString())throw new o0("Should not try to find self");let n=this,o=lr(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new Te}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new vd("No peer routers available");let n=this,o=Nt(1024);for await(let s of Oo((async function*(){let i=lr(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var N0=class extends le{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=de([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=qe(),yield(await Ad(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=de([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=crypto.getRandomValues(new Uint8Array(32)),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ue(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Jy=32,Zy=64,O0=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=gt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new s0(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new i0(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Jy,maxOutboundStreams:Zy,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new A("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var B0=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=gt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=gt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ql.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new A("Transport must have a valid tag");if(this.transports.has(t))throw new A(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new f0(`No transport available for address ${String(e)}`);return t?.onProgress?.(new R("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Cr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new a0)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),k4.matches(c)?t.ipv4.attempts++:_4.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),k4.matches(c)&&t.ipv4.success++,_4.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,d),t.errors.set(c.toString(),d),d}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===ql.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new c0(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
31
|
+
`)),!f.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${f.status} ${f.statusText}`);t.onProgress?.(new R("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Tc(n.toString()),cid:e})),t.onProgress?.(new R("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:e}));let h=await IS(f,o,{signal:i.signal,log:this.log});return t.onProgress?.(new R("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:e})),this.#a++,h}),this.#c.set(s,c)}return await c}catch(c){throw t.signal?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t.signal?.removeEventListener("abort",a),this.#c.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#c.size}}toString(){return`TrustlessGateway(${this.url})`}};var Ay=class extends sc{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Tp,this.allowLocal=t.allowLocal??Cp,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url),n?.onProgress?.(new R("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}));let o;try{o=await t.getRawBlock(e,n),this.log.trace("got block for %c from %s",e,t.url)}finally{n?.onProgress?.(new R("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}))}return await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*Ip(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(n?.signal?.throwIfAborted(),ac(e))return;let o=Sy(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=ks(o[0]);return new Cc(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new R("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function CS(r,e){return new Ay(r,e)}var kp=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Tp,this.allowLocal=t.allowLocal??Cp,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of Ip(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return CS({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Tp=!1,Cp=!1,TS=2097152;function kS(r={}){return e=>new kp(e,r)}var GU=["https://trustless-gateway.link","https://4everland.io"];function _S(r,e){return e?.delegatedRouters??["https://delegated-ipfs.dev"].forEach(t=>{r.addRouter(fS({url:t}))}),r.addRouter(bS({gateways:e?.recursiveGateways??GU})),r.hasBlockBroker("trustless-gateway")||r.addBlockBroker(kS(e?.trustlessGatewayBlockBrokerInit)),r}async function PS(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new A("Private network is enforced, but no protector was provided");return r}var pd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:me(0),payloadType:me(0),payload:me(0),signature:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(pd||(pd={}));var _p=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var qr=class r{static createFromProtobuf=e=>{let t=pd.decode(e),n=Et(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=LS(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new _p("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=pd.encode({publicKey:Lt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:te(this.marshal(),e.marshal())}async validate(e,t){let n=LS(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},LS=(r,e,t)=>{let n=O(r),o=Gt(n.byteLength),s=Gt(e.length),i=Gt(t.length);return new Y(o,n,s,e,i,t)};var DS="libp2p-peer-record",RS=Uint8Array.from([3,1]);var md;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=ae((d,f,h={})=>{h.lengthDelimited!==!1&&f.fork(),d.multiaddr!=null&&d.multiaddr.byteLength>0&&(f.uint32(10),f.bytes(d.multiaddr)),h.lengthDelimited!==!1&&f.ldelim()},(d,f,h={})=>{let p={multiaddr:me(0)},y=f==null?d.len:d.pos+f;for(;d.pos<y;){let g=d.uint32();g>>>3===1?p.multiaddr=d.bytes():d.skipType(g&7)}return p},function*(d,f,h,p={}){let y=f==null?d.len:d.pos+f;for(;d.pos<y;){let g=d.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:d.bytes()}:d.skipType(g&7)}})),a);function c(d){return se(d,i.codec())}i.encode=c;function l(d,f){return oe(d,i.codec(),f)}i.decode=l;function u(d,f){return ie(d,i.codec(),f)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ae((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:me(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new he('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(d&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},d=a==null?i.len:i.pos+a;for(;i.pos<d;){let f=i.uint32();switch(f>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new he('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(f&7);break}}}})),t);function n(i){return se(i,r.codec())}r.encode=n;function o(i,a){return oe(i,r.codec(),a)}r.decode=o;function s(i,a){return ie(i,r.codec(),a)}r.stream=s})(md||(md={}));function NS(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var dr=class r{static createFromProtobuf=e=>{let t=md.decode(e),n=wt(Ee(t.peerId)),o=(t.addresses??[]).map(i=>G(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=DS;static CODEC=RS;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=md.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!NS(this.multiaddrs,e.multiaddrs))}};function jU(r){return r[Symbol.asyncIterator]!=null}function YU(r){if(jU(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Lo=YU;var Pp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Lp=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Vr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function XU(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Dp=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=XU(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Vr),this.cleanup())}async join(e={}){let t=new Lp(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ue(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Iy(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var gd=class extends le{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Iy(this.emitEmpty.bind(this),1),this.emitIdle=Iy(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Pp;let n=new Dp(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Vr)}),this.clear()}async onEmpty(e){this.size!==0&&await Hr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Hr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Hr(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Mt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Vr("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Rp="lock:worker:request-read",Np="lock:worker:abort-read-request",Op="lock:worker:release-read",Bp="lock:master:grant-read",Mp="lock:master:error-read",Up="lock:worker:request-write",Fp="lock:worker:abort-write-request",$p="lock:worker:release-write",Kp="lock:master:grant-write",Vp="lock:master:error-write",Hp="lock:worker:finalize",qp="mortice",OS={singleProcess:!1};var Ty=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let f=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Hp&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var BS=(r=10)=>Math.random().toString().substring(2,r+2);var zp=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(qp)}readLock(e){return this.sendRequest(Rp,Np,Bp,Mp,Op,e)}writeLock(e){return this.sendRequest(Up,Fp,Kp,Vp,$p,e)}finalize(){this.channel.postMessage({type:Hp,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=BS();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=f=>{if(f.data?.identifier===a&&(f.data?.type===n&&(this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),f.data.type===o)){this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u);let h=new Error;f.data.error!=null&&(h.message=f.data.error.message,h.name=f.data.error.name,h.stack=f.data.error.stack),l(h)}};this.channel.addEventListener("message",d)})}};var MS=r=>{if(r=Object.assign({},OS,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(qp),n=new le;return t.addEventListener("message",Ty(n,t,"requestReadLock","abortReadLockRequest",Rp,Np,Mp,Op,Bp)),t.addEventListener("message",Ty(n,t,"requestWriteLock","abortWriteLockRequest",Up,Fp,Vp,$p,Kp)),n}return new zp(r.name)};var ea=new Map,yd;function US(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function QU(r){if(yd==null&&(yd=MS(r),!US(yd))){let e=yd;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=ea.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=ea.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=ea.get(n);o?.finalize()})}return yd}async function Cy(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Vr)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var FS=(r,e)=>{let t=ea.get(r);if(t!=null)return t;let n=QU(e);if(US(n))return t=n,ea.set(r,t),t;let o=new gd({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Cy(s,i);s=new gd({concurrency:e.concurrency,autoStart:!1});let a=s,c=Cy(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Cy(o,i)},finalize:()=>{ea.delete(r)},queue:o},ea.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var JU={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function wd(r){let e=Object.assign({},JU,r);return FS(e.name,e)}var Do;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&f.value.byteLength>0&&(h.uint32(18),h.bytes(f.value)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:"",value:me(0)},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.key=f.string();break}case 2:{y.value=f.bytes();break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield{field:`${p}.value`,value:f.bytes()};break}default:{f.skipType(m&7);break}}}})),c);function l(f){return se(f,a.codec())}a.encode=l;function u(f,h){return oe(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&(h.uint32(18),xd.codec().encode(f.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:""},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.key=f.string();break}case 2:{y.value=xd.codec().decode(f,f.uint32(),{limits:p.limits?.value});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield*xd.codec().stream(f,f.uint32(),`${p}.value`,{limits:y.limits?.value});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return se(f,a.codec())}a.encode=l;function u(f,h){return oe(f,a.codec(),h)}a.decode=u;function d(f,h){return ie(f,a.codec(),h)}a.stream=d})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),bd.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,d]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:d},c);if(a.tags!=null&&a.tags.size>0)for(let[u,d]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:d},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new he('Decode error - repeated field "addresses" had too many elements');u.addresses.push(bd.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new he('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new ru('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new ru('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={addresses:0,protocols:0,metadata:0,tags:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&d.addresses===u.limits.addresses)throw new he('Streaming decode error - repeated field "addresses" had too many elements');for(let p of bd.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:d.addresses};d.addresses++;break}case 2:{if(u.limits?.protocols!=null&&d.protocols===u.limits.protocols)throw new he('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:d.protocols,value:a.string()},d.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&d.metadata===u.limits.metadata)throw new he('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),d.metadata++;break}case 7:{if(u.limits?.tags!=null&&d.tags===u.limits.tags)throw new he('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),d.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Do||(Do={}));var bd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(bd||(bd={}));var xd;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(xd||(xd={}));function ZU(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Et(e.publicKey,t);return Wn(n)}function $S(r,e,t){let n=Do.decode(e);return kc(r,n,t)}function kc(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:ZU(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:G(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function KS(r,e){return eF(r.addresses,e.addresses)&&tF(r.protocols,e.protocols)&&rF(r.publicKey,e.publicKey)&&nF(r.peerRecordEnvelope,e.peerRecordEnvelope)&&oF(r.metadata,e.metadata)&&sF(r.tags,e.tags)}function eF(r,e){return HS(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!te(t.multiaddr,n.multiaddr)))}function tF(r,e){return HS(r,e,(t,n)=>t===n)}function rF(r,e){return VS(r,e)}function nF(r,e){return VS(r,e)}function oF(r,e){return qS(r,e,(t,n)=>te(t,n))}function sF(r,e){return qS(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function VS(r,e){return r==null&&e==null?!0:r!=null&&e!=null?te(r,e):!1}function HS(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function qS(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Ro="/",zS=new TextEncoder().encode(Ro),Wp=zS[0],Me=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=O(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Wp)throw new Error("Invalid key")}toString(e="utf8"){return M(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ro))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=zS),this._buf[0]!==Wp){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Wp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Wp;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ro).slice(1)}type(){return iF(this.baseNamespace())}name(){return aF(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ro)||(e+=Ro),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ro):new r(e.slice(0,-1).join(Ro))}child(e){return this.toString()===Ro?e:e.toString()===Ro?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...cF(e.map(t=>t.namespaces()))])}};function iF(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function aF(r){let e=r.split(":");return e[e.length-1]}function cF(r){return[].concat(...r)}var ky="/peers/";function Ed(r){if(!yr(r)||r.type==null)throw new A("Invalid PeerId");let e=r.toCID().toString();return new Me(`${ky}${e}`)}async function WS(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=G(i.multiaddr)),!jr(i.multiaddr))throw new A("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(G(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function jp(r,e,t,n){if(e==null)throw new A("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new A("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new A("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Gp(f,{validate:GS})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Gp(f,{validate:jS,map:YS})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=Gp([...a.entries()],{validate:GS})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,y]of f)y==null?h.delete(p):h.set(p,y);c=Gp([...h.entries()],{validate:jS,map:YS})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Lt(o.id.publicKey):e.publicKey!=null?u=Lt(e.publicKey):r.publicKey!=null&&(u=Lt(r.publicKey));let d={addresses:await WS(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=n.existingPeer?.peerPB.addresses?.find(h=>te(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function Gp(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function GS(r,e){if(typeof r!="string")throw new A("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new A("Metadata value must be a Uint8Array")}function jS(r,e){if(typeof r!="string")throw new A("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new A("Tag value must be an integer");if(e.value<0||e.value>100)throw new A("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new A("Tag ttl must be an integer");if(e.ttl<0)throw new A("Tag ttl must be between greater than 0")}}function YS(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function XS(r){let e=r.toString().split("/")[2],t=K.parse(e,pt);return vt(t)}function _y(r,e,t){let n=XS(r);return $S(n,e,t)}function lF(r,e){return{prefix:ky,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(_y(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(_y(n.key,n.value,e),_y(o.key,o.value,e)))}}var Yp=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=_o({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:wd({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Ed(e),t)}async load(e,t){let n=Ed(e),o=await this.datastore.get(n,t),s=Do.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Te;return kc(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await jp(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await jp(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await jp(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(lF(e??{},this.maxAddressAge),e)){let o=XS(t);if(o.equals(this.peerId))continue;let s=Do.decode(n);if(this.#r(o,s)){await this.datastore.delete(t,e);continue}yield kc(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Ed(e),o=await this.datastore.get(n,t),s=Do.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Te;return{peerPB:s,peer:kc(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Do.encode(t);return await this.datastore.put(Ed(e),s,o),{peer:kc(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!KS(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Py=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Yp(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Lo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=yr(t)?t:yr(t?.expectedPeer)?t.expectedPeer:void 0,s=yr(t)||t===void 0?n:t,i=await qr.openAndCertify(e,dr.DOMAIN,s),a=vt(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=dr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=qr.createFromProtobuf(l.peerRecordEnvelope),d=dr.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function QS(r,e={}){return new Py(r,e)}var tn=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function uF(r){return r[Symbol.asyncIterator]!=null}function dF(r,e){return uF(r)?(async function*(){yield*(await Lo(r)).sort(e)})():(function*(){yield*Lo(r).sort(e)})()}var Xp=dF;var No=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Er(this.putMany(e,n)),e=[],await Er(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Br(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xp(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Br(n,()=>o++>=s)}return e.limit!=null&&(n=Ts(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Br(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xp(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Br(n,()=>s++>=o)}return e.limit!=null&&(n=Ts(n,e.limit)),n}};var ta=class extends No{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new tn;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Me(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Me(n),t?.signal?.throwIfAborted()}};var JS=864e13;var Qp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=gt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=ce(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Ma(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?JS-Date.now():0,lastVerified:o?JS-Date.now():void 0})})}remove(e){let t=ce(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Ot(o))continue;let s=ce(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),G(n)}confirm(e,t){let n=ce(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=ce(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Jp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=gt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=ce(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:hn(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=ce(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Ot(n))continue;let o=ce(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,G(i)):e}confirm(e,t){if(!Ot(e))return!1;let n=ce(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!Ot(e))return!1;let n=ce(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var fF={maxObservedAddresses:10},Zp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??fF.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(it(e)||h9(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:G(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var hF={maxObservedAddresses:10},em=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=gt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??hF.maxObservedAddresses}get(e,t){if(it(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Ot(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!Ot(e))return e.toString();let t=ce(e);return`${t.host}-${t.port}-${t.protocol}`}};var ZS=6e4,eA={maxObservedAddresses:10,addressVerificationTTL:ZS*10,addressVerificationRetry:ZS*5},pF=r=>r;function Ly(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&Xe(t).equals(e)&&(r=r.decapsulate(G(`/p2p/${e.toString()}`))),r}var tm=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Zp(e,t),this.dnsMappings=new Qp(e,t),this.ipMappings=new Jp(e,t),this.transportAddresses=new em(e,t),this.announceFilter=t.announceFilter??pF,this.observedAddressFilter=Nt(1024),this.addressVerificationTTL=t.addressVerificationTTL??eA.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??eA.addressVerificationRetry,this._updatePeerStoreAddresses=bo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>G(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>G(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>G(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=ce(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Ly(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Ly(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Ly(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=G(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(G(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${hn(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(G(`/ip${hn(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Ot(e))return!1;let t=ce(e);if(t.type!=="ip4"||Ma(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>wo.exactMatch(s)||Ai.exactMatch(s),s=>Si.exactMatch(s),s=>M9.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>ce(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!pu(l)).pop();if(a==null)continue;let c=ce(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var tA;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(tA||(tA={}));var rm=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},nm=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},_c=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},vd=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},om=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},sm=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},im=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Sd=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},am=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},cm=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},lm=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},um=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},dm=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},_s=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},ra=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},fm=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},hm=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Dy=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=tc())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>wh(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},mF=["metrics","connectionProtector","dns"],gF=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function rA(r={}){let e=new Dy(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!gF.includes(o)){let i=e.components[o];if(i==null&&!mF.includes(o))throw new rm(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function nA(r){let e={};for(let t of Object.values(r.components))for(let n of yF(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of wF(t))if(e[n]!==!0)throw new nm(`Service "${bF(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function yF(r){return Array.isArray(r?.[xe])?r[xe]:[]}function wF(r){return Array.isArray(r?.[kr])?r[kr]:[]}function bF(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function oA(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>wo.matches(e)?!0:it(e)),r}var xF=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 EF(r,e,t){let n,o=new Promise((s,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}=xF(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=cr(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ad(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=EF(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function pm(r){if(yr(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:Xe(n),e.forEach(o=>{if(!jr(o))throw new On("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new A("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Xe(s);if(t?.equals(i)!==!0)throw new A("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!D9.exactMatch(n)),{peerId:t,multiaddrs:e}}var vF=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function sA(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??vF;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Id(r){let e=ce(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new A(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new A(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new bi(e.host,t)}function Ry(r){return!_t.exactMatch(r)}function mm(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Ry(s)))return n}var gm=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Id(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Jt;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(Ot(c.remoteAddr)){let d=ce(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await sA(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var iA="last-dial-failure",aA="last-dial-success";var cA=100,ym=50;function SF(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function lA(r){return r.sort((e,t)=>z9(e.multiaddr,t.multiaddr)||W9(e.multiaddr,t.multiaddr)||G9(e.multiaddr,t.multiaddr)||SF(e,t)||q9(e.multiaddr,t.multiaddr))}var wm=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"},bm=class extends AggregateError{static name="EmptyDNSAnswerError";name="EmptyDNSAnswerError"};var Oy=ti(dA(),1);function By(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var TF=100,Pc=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#r();let a=By(this.#e,i,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>TF&&this.#t>this.#e.length/2&&this.#r(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#r(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Cd=class extends Oy.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#u;#C=0;#x=0;#d;#f;#l;#i=[];#s=0;#n;#k;#o=0;#y;#h;#R=1n;#w=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Pc,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#u=e.interval,this.#l=e.strict,this.#n=new e.queueClass,this.#k=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#h=e.autoStart===!1,this.#K()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#u)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#N(e){this.#l?this.#i.push(e):this.#r++}#O(){this.#l?this.#i.length>this.#s&&this.#i.pop():this.#r>0&&this.#r--}#S(){return this.#i.length-this.#s}get#B(){return this.#t?!0:this.#l?this.#S()<this.#a:this.#r<this.#a}get#M(){return this.#o<this.#y}#U(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#f=void 0,this.#L(),this.#P()}#$(e){if(this.#l){if(this.#v(e),this.#S()>=this.#a){let n=this.#i[this.#s],o=this.#u-(e-n);return this.#A(o),!0}return!1}if(this.#d===void 0){let t=this.#C-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#u)return this.#A(this.#u-n),!0}this.#r=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#F()},e))}#I(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}#_(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#b(){if(this.#n.size===0){if(this.#I(),this.emit("empty"),this.#o===0){if(this.#_(),this.#l&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#h){let t=Date.now(),n=!this.#$(t);if(this.#B&&this.#M){let o=this.#n.dequeue();this.#t||(this.#N(t),this.#g()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#t||this.#d!==void 0||this.#l||(this.#d=setInterval(()=>{this.#L()},this.#u),this.#C=Date.now()+this.#u)}#L(){this.#l||(this.#r===0&&this.#o===0&&this.#d&&this.#I(),this.#r=this.#e?this.#o:0),this.#T(),this.#g()}#T(){for(;this.#b(););}get concurrency(){return this.#y}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#T()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#n.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#w.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(f){throw this.#V(),this.#w.delete(s),f}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=cr(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:f}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(f.reason)},f.addEventListener("abort",l,{once:!0})})])}let d=await u;n(d),this.emit("completed",d)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#w.delete(s),queueMicrotask(()=>{this.#U()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof Pc){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),o(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#E.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#T(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#n=new this.#k,this.#I(),this.#D(),this.emit("empty"),this.#o===0&&(this.#_(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#h}#K(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#D()}))}#V(){this.#t||(this.#O(),this.#g())}#D(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#l){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Em(r){let e=[zr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var My=60;function vm(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:zr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:zr[e.type],TTL:e.TTL??e.ttl??My,data:e.data instanceof Uint8Array?M(e.data):e.data}))}}var CF=4;function Uy(r,e={}){let t=new Cd({concurrency:e.queryConcurrency??CF});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Em(o.types).forEach(c=>{i.append("type",zr[c])}),o.onProgress?.(new R("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=vm(await c.json());return o.onProgress?.(new R("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function fA(){return[Uy("https://cloudflare-dns.com/dns-query"),Uy("https://dns.google/resolve")]}var mA=ti(pA(),1);var Fy=class{lru;constructor(e){this.lru=(0,mA.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return vm({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:zr[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??My)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function gA(r){return new Fy(r)}var kF=1e3,_F=()=>Math.random()>.5?-1:1,Sm=class{resolvers;cache;logger;sorter;constructor(e){this.resolvers={},this.cache=gA(e.cacheSize??kF),this.logger=e.logger,this.sorter=e.sorter??_F,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=fA())}async query(e,t={}){let n=Em(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new R("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(this.sorter),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});if(l.Answer.length===0)throw new bm("Query result had no answers");for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new R("dns:error",l))}}throw new wm(a,`DNS lookup of ${e} ${n} failed`)}};var zr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(zr||(zr={}));function Am(r={}){return new Sm(r)}var $y=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[zr.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(G(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Am()),this.dns)}},kd=new $y;async function Ky(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new hm("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Ky(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Lc={maxParallelDials:ym,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:kd}},Im=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??Lc.addressDialTimeout,this.connections=t.connections??new Jt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Lc.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new _1({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==nr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=pm(e);if(n!=null&&t.force!==!0){let i=mm(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new R("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new R("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Zo("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new R("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new R("dial-queue:start-dial"));let a=de([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Wy,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],d=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let f=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let h of f){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new R("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Zo("Peer had more than maxPeerAddrsToDial");a++;let p=de([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let y=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(y.remotePeer,{multiaddrs:[y.remoteAddr],metadata:{[aA]:O(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return y}catch(y){if(this.log.error("dial failed to %a - %e",h.multiaddr,y),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[iA]:O(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new Bn(y.message);l.push(y)}finally{p.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(d=>({multiaddr:G(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Zo("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Sd("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);o.push(...d.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let s=(await Promise.all(o.map(async d=>{let f=await Ky(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;s=s.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}let i=s.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let f=d.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let d of i){let f=d.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||d.isCertified||!1;continue}a.set(f,d)}let c=[...a.values()];if(c.length===0)throw new lm(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?lA(l):l.sort(this.addressSorter);if(u.length===0)throw new Sd(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!_t.matches(o.multiaddr))!=null:!0}catch{}return!1}};var PF=Object.prototype.toString,LF=r=>PF.call(r)==="[object Error]",DF=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Gy(r){if(!(r&&LF(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:DF.has(t)}function RF(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Tm(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function jy(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var Yy=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function NF(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function Cm(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function OF(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function BF({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof Yy)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=NF(t,o);if(Cm(n,a)<=0){let m=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(m),s}let u=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),d=await o.shouldConsumeRetry(u),f=d&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:f});if(await o.onFailedAttempt(h),Cm(n,a)<=0||Cm(n,a)<=0||i<=0||s instanceof TypeError&&!Gy(s)||!await o.shouldRetry(h))throw s;let y=Cm(n,a);if(y<=0)throw s;if(!d)return o.signal?.throwIfAborted(),!1;let g=Math.min(f,y);return o.signal?.throwIfAborted(),await OF(g,o),o.signal?.throwIfAborted(),!0}async function Xy(r,e={}){if(e={...e},RF(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,jy("onFailedAttempt",e.onFailedAttempt),jy("shouldRetry",e.shouldRetry),jy("shouldConsumeRetry",e.shouldConsumeRetry),Tm("factor",e.factor,{min:0,allowInfinity:!1}),Tm("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Tm("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Tm("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await BF({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var km=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Xt({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);yA(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Xy(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(ci)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>yA(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function yA(r){for(let e of r.tags.keys())if(e.startsWith(ci))return!0;return!1}var Wy=50,Qy={maxConnections:cA,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},_m=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Qy.maxConnections,this.maxConnections<1)throw new A("Connection Manager maxConnections must be greater than 0");this.connections=new Jt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Id(G(n))),this.deny=(t.deny??[]).map(n=>Id(G(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Qy.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new nc({points:t.inboundConnectionThreshold??Qy.inboundConnectionThreshold,duration:1}),this.connectionPruner=new gm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>G(n))}),this.dialQueue=new Im(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ym,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:kd},connections:this.connections}),this.reconnectQueue=new km({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await ht(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Ct(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([Ad(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new A("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Cr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new R("connection:open",e));let{peerId:n,multiaddrs:o}=pm(e);if(this.peerId.equals(n))throw new Ea("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=mm(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new R("dial-queue:already-connected")),t.onProgress?.(new R("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Wy});if(s.status!=="open")throw new ni("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new On("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new R("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([Ad(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Ot(e.remoteAddr)){let s=ce(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Ot(e.remoteAddr)){let s=ce(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Ot(e.remoteAddr)){let o=ce(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>G(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var FF=1e4,$F="1.0.0",KF="ping",VF="ipfs",wA=32,HF=!0,Pm=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??VF}/${KF}/${$F}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??FF,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??HF,this.timeout=new yn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xe]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=a1(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(wA)),{signal:n}),s.read({bytes:wA,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Lm=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new _c("No content routers available");let n=this,o=new Kr;for await(let s of lr(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new _c("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new _c("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Cr;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Cr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Dm=globalThis.CustomEvent??Event;async function*Oo(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=qe(),a=qe(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=qe(),await i.promise),u)break;let y={done:!1};s.push(y),p().then(g=>{y.done=!0,y.ok=!0,y.value=g,o.dispatchEvent(new Dm("task-complete"))},g=>{y.done=!0,y.err=g,o.dispatchEvent(new Dm("task-complete"))})}c=!0,o.dispatchEvent(new Dm("task-complete"))}catch(p){l=p,o.dispatchEvent(new Dm("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(p=>p.done)}function*f(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;d();)for(let p=0;p<s.length;p++)if(s[p].done){let y=s[p];if(s.splice(p,1),p--,y.ok)yield y.value;else throw u=!0,i.resolve(),y.err;i.resolve()}}for(;;){if(d()||(a=qe(),await a.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var Rm=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:M(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new vd("No peer routers available");if(e.toString()===this.peerId.toString())throw new om("Should not try to find self");let n=this,o=lr(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new Te}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new vd("No peer routers available");let n=this,o=Nt(1024);for await(let s of Oo((async function*(){let i=lr(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Nm=class extends le{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=de([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=qe(),yield(await Ad(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=de([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=crypto.getRandomValues(new Uint8Array(32)),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ue(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Jy=32,Zy=64,Om=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=gt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new sm(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new im(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Jy,maxOutboundStreams:Zy,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new A("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Bm=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=gt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=gt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ql.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new A("Transport must have a valid tag");if(this.transports.has(t))throw new A(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new fm(`No transport available for address ${String(e)}`);return t?.onProgress?.(new R("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Cr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new am)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),k4.matches(c)?t.ipv4.attempts++:_4.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),k4.matches(c)&&t.ipv4.success++,_4.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,d),t.errors.set(c.toString(),d),d}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===ql.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new cm(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
32
32
|
${[...t.errors.entries()].map(([s,i])=>`
|
|
33
33
|
${s}: ${`${qF(i)}`.split(`
|
|
34
34
|
`).join(`
|
|
@@ -42,12 +42,12 @@ ${[...t.errors.entries()].map(([s,i])=>`
|
|
|
42
42
|
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Y(...e.map(a=>Eo.single(O(`${a}
|
|
43
43
|
`))),O(`
|
|
44
44
|
`));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(O(`na
|
|
45
|
-
`),t),n('responded with "na" for "%s"',s)}}var t8=class extends le{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Ry(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new es(n.local,n.error))})}[Symbol.toStringTag]="Connection";[gb]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new _s("Connection is not multiplexed");if(this.muxer.status!=="open")throw new ni(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new ni(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Hl("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new R("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Dc(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=jF(n.protocol,this.components.registrar,t),s=EA(n.protocol,"outbound",this);if(s>o){let c=new Sa(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new R("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Rc(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=GF(t.protocol,this.components.registrar);if(EA(t.protocol,"inbound",this)>o)throw new hh(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Hl("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function vA(r,e){return new t8(r,e)}function GF(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Jy}function jF(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Zy}function EA(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var M0=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=gt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=gt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new u0(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=de([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new d0("Connection denied");await Ue(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=Xe(n),await Ue(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(YF(n)){if(n.remotePeer==null)throw new On(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,f;d!=null&&(f=Xe(d)),n?.onProgress?.(new R(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:f}):this._encryptOutbound(o,{...n,remotePeer:f}))}if(s.equals(this.components.peerId)){let d=new Ea("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new R(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=vA(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Rc(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new ra(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new ra(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Dc(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new ra(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new ra(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Dc(e,o,n),i=t.get(s);if(i==null)throw new _s(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new _s(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Rc(e,o,n),i=t.get(s);if(i==null)throw new _s(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function YF(r){return r.skipEncryption===!0}var U0="3.3.4",F0="js-libp2p";function $0(r,e){return`${r??F0}/${e??U0} browser/${globalThis.navigator.userAgent}`}var Pd=class extends le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new le,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??tc(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??F0,s=e.nodeInfo?.version??U0,i=this.components=rA({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??$0(o,s)},logger:this.logger,events:t,datastore:e.datastore??new ta,connectionGater:oA(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",QS(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new M0(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new B0(this.components,e.transportManager)),this.configureComponent("connectionManager",new _0(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new P0(this.components,e.connectionMonitor)),this.configureComponent("registrar",new O0(this.components)),this.configureComponent("addressManager",new t0(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new R0(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new L0(this.components,{routers:c})),this.configureComponent("randomWalk",new N0(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[ri]!=null&&(this.log("registering service %s for content routing",l),c.push(d[ri])),d[ai]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[ai])),d[ii]!=null&&(this.log("registering service %s for peer discovery",l),d[ii].addEventListener?.("peer",f=>{this.#e(f)}))}nA(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Kr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new A("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new A("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){jr(e)&&(e=Xe(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ke([O("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Et(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function AA(r={}){r.privateKey??=await rp("Ed25519");let e=new Pd({...await PS(r),peerId:eS(r.privateKey)});return r.start!==!1&&await e.start(),e}var XF=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function r8(r){return r==null?!1:r instanceof Pd?!0:XF.every(e=>typeof r[e]=="function")}function n8(r){return{...r,id:r.id.toCID()}}var o8=class{name="libp2p-router";libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*Kt(this.libp2p.contentRouting.findProviders(e,t),n=>({routing:this.name,...n8(n)}))}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return ee(await this.libp2p.contentRouting.get(e,t))}async findPeer(e,t){return n8(await this.libp2p.peerRouting.findPeer(vt(e),t))}async*getClosestPeers(e,t){yield*Kt(this.libp2p.peerRouting.getClosestPeers(e,t),n8)}toString(){return"Libp2pRouter()"}};function IA(r){return new o8(r)}var Ld=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ps=new Uint32Array(80),s8=class extends Oi{A=Ld[0]|0;B=Ld[1]|0;C=Ld[2]|0;D=Ld[3]|0;E=Ld[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ps[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ps[c]=U1(Ps[c-3]^Ps[c-8]^Ps[c-14]^Ps[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=$1(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=K1(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let d=U1(n,5)+l+a+u+Ps[c]|0;a=i,i=s,s=U1(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){Qt(Ps)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),Qt(this.buffer)}},TA=$u(()=>new s8);function CA(r,e,t,n){Ao(r);let o=OE({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(xr(s,"c"),xr(i,"dkLen"),xr(a,"asyncTick"),s<1)throw new Error("iterations (c) must be >= 1");if(i<1)throw new Error('"dkLen" must be >= 1');if(i>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=d6(e,"password"),l=d6(t,"salt"),u=new Uint8Array(i),d=Wi.create(r,c),f=d._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function kA(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),Qt(o),t}function _A(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=CA(r,e,t,n),l,u=new Uint8Array(4),d=Ni(u),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<s;h++,p+=a.outputLen){let y=i.subarray(p,p+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let m=0;m<y.length;m++)y[m]^=f[m]}}return kA(a,c,i,l,f)}async function K0(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=CA(r,e,t,n),u,d=new Uint8Array(4),f=Ni(d),h=new Uint8Array(c.outputLen);for(let p=1,y=0;y<s;p++,y+=c.outputLen){let g=a.subarray(y,y+c.outputLen);f.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(h),g.set(h.subarray(0,g.length)),await NE(o-1,i,()=>{c._cloneInto(u).update(h).digestInto(h);for(let m=0;m<g.length;m++)g[m]^=h[m]})}return kA(c,l,a,u,h)}var PA={sha1:TA,"sha2-256":Zr,"sha2-512":Hn};function Dd(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(PA).join(" / ");throw new A(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let s=PA[o],i=_A(s,r,e,{c:t,dkLen:n});return $e.encode(i).substring(1)}var _I=ti(i8(),1);var a8={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var Nc={};V(Nc,{create:()=>l$,derivedEmptyPasswordKey:()=>V0});var V0={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function l$(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=yt.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:p};typeof f=="string"&&(f=O(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",V0,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",V0,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["encrypt"])}let m=await a.subtle.encrypt(y,g,ee(d));return Ke([h,y.iv,new Uint8Array(m)])}async function l(d,f){let h=d.subarray(0,s),p=d.subarray(s,s+n),y=d.subarray(s+n),g={name:e,iv:p};typeof f=="string"&&(f=O(f));let m;if(f.length===0)try{let x={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}catch{m=await a.subtle.importKey("jwk",V0,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}let w=await a.subtle.decrypt(g,m,ee(y));return new Uint8Array(w)}return{encrypt:c,decrypt:l}}var ve=ti(FA());function na(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Ls(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/d),o-=l[s-u-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function z0(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function l8(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=na(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,na(s,8)-n}function $A(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Ls(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ls(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function KA(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function vr(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Tge=Math.log(2);function W0(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function u8(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ko(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Od=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return u8(this.items)}},Rd=[new Uint8Array([1])],VA="0123456789";var Bc="",Xn=new ArrayBuffer(0),d8=new Uint8Array(0),Bd="EndOfContent",qA="OCTET STRING",zA="BIT STRING";function Vo(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?ve.BufferSourceConverter.toUint8Array(s.valueHex):d8}fromBER(n,o,s,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ko(this,a,o,s))return-1;let c=o+s;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Xn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ve.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Mo=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=Bc,warnings:n=[],valueBeforeDecode:o=d8}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ve.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ve.Convert.ToHex(this.valueBeforeDecodeView)}}};Mo.NAME="baseBlock";var Vt=class extends Mo{fromBER(e,t,n,o){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Vt.NAME="valueBlock";var G0=class extends Vo(Mo){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ve.BufferSourceConverter.toUint8Array(e.valueHex):d8,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Xn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Ls(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(s[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=s[u+1]&127;this.blockLength<=9?this.tagNumber=na(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};G0.NAME="identificationBlock";var j0=class extends Mo{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=na(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Ls(this.length,8);if(o.byteLength>127)return this.error="Too big length",Xn;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};j0.NAME="lengthBlock";var J={},Rt=class extends Mo{constructor({name:e=Bc,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new G0(o),this.lenBlock=new j0(o),this.valueBlock=s?new s(o):new Vt(o)}fromBER(e,t,n,o){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){let n=t||new Od;t||WA(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?Xn:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ve.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=ve.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return KA(t,n)}};Rt.NAME="BaseBlock";function WA(r){var e;if(r instanceof J.Constructed)for(let t of r.valueBlock.value)WA(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var Y0=class extends Rt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Bc,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Y0.NAME="BaseStringBlock";var X0=class extends Vo(Vt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};X0.NAME="PrimitiveValueBlock";var GA,Q0=class extends Rt{constructor(e={}){super(e,X0),this.idBlock.isConstructed=!1}};GA=Q0;J.Primitive=GA;Q0.NAME="PRIMITIVE";var w$=100,b$=1e4,x$=16*1024*1024,E$="Maximum ASN.1 nesting depth exceeded",v$="Maximum ASN.1 node count exceeded",S$="Maximum ASN.1 content length exceeded";function Vd(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:w$,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:b$,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:x$}}function A$(r){let e=new Rt({},Vt);return e.error=r,{offset:-1,result:e}}function I$(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return v$}function T$(r,e){if(r>e.maxContentLength)return S$}function f8(r,e,t,n){let o=n.depth+1;if(o>n.maxDepth)return A$(E$);n.depth=o;try{return jA(r,e,t,n)}finally{n.depth-=1}}function C$(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function jA(r,e=0,t=r.length,n=Vd()){let o=e,s=new Rt({},Vt),i=new Mo;if(!Ko(i,r,e,t))return s.error=i.error,{offset:-1,result:s};if(!r.subarray(e,e+t).length)return s.error="Zero buffer length",{offset:-1,result:s};let c=I$(n);if(c)return s.error=c,{offset:-1,result:s};let l=s.idBlock.fromBER(r,e,t);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),l===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=l,t-=s.idBlock.blockLength,l=s.lenBlock.fromBER(r,e,t),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),l===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};e=l,t-=s.lenBlock.blockLength;let u=s.lenBlock.isIndefiniteForm?t:s.lenBlock.length,d=T$(u,n);if(d)return s.error=d,{offset:-1,result:s};if(!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let f=Rt;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};f=J.EndOfContent;break;case 1:f=J.Boolean;break;case 2:f=J.Integer;break;case 3:f=J.BitString;break;case 4:f=J.OctetString;break;case 5:f=J.Null;break;case 6:f=J.ObjectIdentifier;break;case 10:f=J.Enumerated;break;case 12:f=J.Utf8String;break;case 13:f=J.RelativeObjectIdentifier;break;case 14:f=J.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:f=J.Sequence;break;case 17:f=J.Set;break;case 18:f=J.NumericString;break;case 19:f=J.PrintableString;break;case 20:f=J.TeletexString;break;case 21:f=J.VideotexString;break;case 22:f=J.IA5String;break;case 23:f=J.UTCTime;break;case 24:f=J.GeneralizedTime;break;case 25:f=J.GraphicString;break;case 26:f=J.VisibleString;break;case 27:f=J.GeneralString;break;case 28:f=J.UniversalString;break;case 29:f=J.CharacterString;break;case 30:f=J.BmpString;break;case 31:f=J.DATE;break;case 32:f=J.TimeOfDay;break;case 33:f=J.DateTime;break;case 34:f=J.Duration;break;default:{let h=s.idBlock.isConstructed?new J.Constructed:new J.Primitive;h.idBlock=s.idBlock,h.lenBlock=s.lenBlock,h.warnings=s.warnings,s=h}}break;default:f=s.idBlock.isConstructed?J.Constructed:J.Primitive}return s=C$(s,f),l=s.fromBER(r,e,u,n),s.valueBeforeDecodeView=r.subarray(o,o+s.blockLength),{offset:l,result:s}}function Lm(r,e={}){if(!r.byteLength){let t=new Rt({},Vt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return jA(ve.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,Vd(e))}function k$(r,e){return r?1:e}var jn=class extends Vt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,o){let s=ve.BufferSourceConverter.toUint8Array(e),i=o??Vd();if(!Ko(this,s,t,n))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;k$(this.isIndefiniteForm,n)>0;){let c=f8(s,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Bd)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Bd?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new Od;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Xn:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};jn.NAME="ConstructedValueBlock";var YA,Ds=class extends Rt{constructor(e={}){super(e,jn),this.idBlock.isConstructed=!0}fromBER(e,t,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
45
|
+
`),t),n('responded with "na" for "%s"',s)}}var t8=class extends le{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Ry(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new es(n.local,n.error))})}[Symbol.toStringTag]="Connection";[gb]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new _s("Connection is not multiplexed");if(this.muxer.status!=="open")throw new ni(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new ni(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Hl("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new R("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Dc(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=jF(n.protocol,this.components.registrar,t),s=EA(n.protocol,"outbound",this);if(s>o){let c=new Sa(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new R("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Rc(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=GF(t.protocol,this.components.registrar);if(EA(t.protocol,"inbound",this)>o)throw new hh(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Hl("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function vA(r,e){return new t8(r,e)}function GF(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Jy}function jF(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Zy}function EA(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Mm=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=gt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=gt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new um(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=de([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new dm("Connection denied");await Ue(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=Xe(n),await Ue(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(YF(n)){if(n.remotePeer==null)throw new On(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,f;d!=null&&(f=Xe(d)),n?.onProgress?.(new R(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:f}):this._encryptOutbound(o,{...n,remotePeer:f}))}if(s.equals(this.components.peerId)){let d=new Ea("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new R(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=vA(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Rc(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new ra(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new ra(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Dc(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new ra(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new ra(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Dc(e,o,n),i=t.get(s);if(i==null)throw new _s(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new _s(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Rc(e,o,n),i=t.get(s);if(i==null)throw new _s(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function YF(r){return r.skipEncryption===!0}var Um="3.3.4",Fm="js-libp2p";function $m(r,e){return`${r??Fm}/${e??Um} browser/${globalThis.navigator.userAgent}`}var Pd=class extends le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new le,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??tc(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Fm,s=e.nodeInfo?.version??Um,i=this.components=rA({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??$m(o,s)},logger:this.logger,events:t,datastore:e.datastore??new ta,connectionGater:oA(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",QS(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Mm(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Bm(this.components,e.transportManager)),this.configureComponent("connectionManager",new _m(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Pm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Om(this.components)),this.configureComponent("addressManager",new tm(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Rm(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Lm(this.components,{routers:c})),this.configureComponent("randomWalk",new Nm(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[ri]!=null&&(this.log("registering service %s for content routing",l),c.push(d[ri])),d[ai]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[ai])),d[ii]!=null&&(this.log("registering service %s for peer discovery",l),d[ii].addEventListener?.("peer",f=>{this.#e(f)}))}nA(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Kr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new A("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new A("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){jr(e)&&(e=Xe(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ke([O("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Et(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function AA(r={}){r.privateKey??=await rp("Ed25519");let e=new Pd({...await PS(r),peerId:eS(r.privateKey)});return r.start!==!1&&await e.start(),e}var XF=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function r8(r){return r==null?!1:r instanceof Pd?!0:XF.every(e=>typeof r[e]=="function")}function n8(r){return{...r,id:r.id.toCID()}}var o8=class{name="libp2p-router";libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*Kt(this.libp2p.contentRouting.findProviders(e,t),n=>({routing:this.name,...n8(n)}))}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return ee(await this.libp2p.contentRouting.get(e,t))}async findPeer(e,t){return n8(await this.libp2p.peerRouting.findPeer(vt(e),t))}async*getClosestPeers(e,t){yield*Kt(this.libp2p.peerRouting.getClosestPeers(e,t),n8)}toString(){return"Libp2pRouter()"}};function IA(r){return new o8(r)}var Ld=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ps=new Uint32Array(80),s8=class extends Oi{A=Ld[0]|0;B=Ld[1]|0;C=Ld[2]|0;D=Ld[3]|0;E=Ld[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ps[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ps[c]=U1(Ps[c-3]^Ps[c-8]^Ps[c-14]^Ps[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=$1(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=K1(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let d=U1(n,5)+l+a+u+Ps[c]|0;a=i,i=s,s=U1(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){Qt(Ps)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),Qt(this.buffer)}},TA=$u(()=>new s8);function CA(r,e,t,n){Ao(r);let o=OE({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(xr(s,"c"),xr(i,"dkLen"),xr(a,"asyncTick"),s<1)throw new Error("iterations (c) must be >= 1");if(i<1)throw new Error('"dkLen" must be >= 1');if(i>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=d6(e,"password"),l=d6(t,"salt"),u=new Uint8Array(i),d=Wi.create(r,c),f=d._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function kA(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),Qt(o),t}function _A(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=CA(r,e,t,n),l,u=new Uint8Array(4),d=Ni(u),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<s;h++,p+=a.outputLen){let y=i.subarray(p,p+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let m=0;m<y.length;m++)y[m]^=f[m]}}return kA(a,c,i,l,f)}async function Km(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=CA(r,e,t,n),u,d=new Uint8Array(4),f=Ni(d),h=new Uint8Array(c.outputLen);for(let p=1,y=0;y<s;p++,y+=c.outputLen){let g=a.subarray(y,y+c.outputLen);f.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(h),g.set(h.subarray(0,g.length)),await NE(o-1,i,()=>{c._cloneInto(u).update(h).digestInto(h);for(let m=0;m<g.length;m++)g[m]^=h[m]})}return kA(c,l,a,u,h)}var PA={sha1:TA,"sha2-256":Zr,"sha2-512":Hn};function Dd(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(PA).join(" / ");throw new A(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let s=PA[o],i=_A(s,r,e,{c:t,dkLen:n});return $e.encode(i).substring(1)}var _I=ti(i8(),1);var a8={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var Nc={};V(Nc,{create:()=>l$,derivedEmptyPasswordKey:()=>Vm});var Vm={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function l$(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=yt.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:p};typeof f=="string"&&(f=O(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",Vm,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",Vm,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,x,{name:e,length:t},!0,["encrypt"])}let m=await a.subtle.encrypt(y,g,ee(d));return Ke([h,y.iv,new Uint8Array(m)])}async function l(d,f){let h=d.subarray(0,s),p=d.subarray(s,s+n),y=d.subarray(s+n),g={name:e,iv:p};typeof f=="string"&&(f=O(f));let m;if(f.length===0)try{let x={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}catch{m=await a.subtle.importKey("jwk",Vm,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ee(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}let w=await a.subtle.decrypt(g,m,ee(y));return new Uint8Array(w)}return{encrypt:c,decrypt:l}}var ve=ti(FA());function na(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Ls(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/d),o-=l[s-u-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function zm(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function l8(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=na(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,na(s,8)-n}function $A(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Ls(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ls(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function KA(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function vr(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Tge=Math.log(2);function Wm(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function u8(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ko(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Od=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return u8(this.items)}},Rd=[new Uint8Array([1])],VA="0123456789";var Bc="",Xn=new ArrayBuffer(0),d8=new Uint8Array(0),Bd="EndOfContent",qA="OCTET STRING",zA="BIT STRING";function Vo(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?ve.BufferSourceConverter.toUint8Array(s.valueHex):d8}fromBER(n,o,s,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ko(this,a,o,s))return-1;let c=o+s;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Xn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ve.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Mo=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=Bc,warnings:n=[],valueBeforeDecode:o=d8}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ve.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ve.Convert.ToHex(this.valueBeforeDecodeView)}}};Mo.NAME="baseBlock";var Vt=class extends Mo{fromBER(e,t,n,o){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Vt.NAME="valueBlock";var Gm=class extends Vo(Mo){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ve.BufferSourceConverter.toUint8Array(e.valueHex):d8,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Xn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Ls(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(s[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=s[u+1]&127;this.blockLength<=9?this.tagNumber=na(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Gm.NAME="identificationBlock";var jm=class extends Mo{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=na(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Ls(this.length,8);if(o.byteLength>127)return this.error="Too big length",Xn;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};jm.NAME="lengthBlock";var J={},Rt=class extends Mo{constructor({name:e=Bc,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Gm(o),this.lenBlock=new jm(o),this.valueBlock=s?new s(o):new Vt(o)}fromBER(e,t,n,o){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){let n=t||new Od;t||WA(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?Xn:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ve.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=ve.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return KA(t,n)}};Rt.NAME="BaseBlock";function WA(r){var e;if(r instanceof J.Constructed)for(let t of r.valueBlock.value)WA(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var Ym=class extends Rt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Bc,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Ym.NAME="BaseStringBlock";var Xm=class extends Vo(Vt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Xm.NAME="PrimitiveValueBlock";var GA,Qm=class extends Rt{constructor(e={}){super(e,Xm),this.idBlock.isConstructed=!1}};GA=Qm;J.Primitive=GA;Qm.NAME="PRIMITIVE";var w$=100,b$=1e4,x$=16*1024*1024,E$="Maximum ASN.1 nesting depth exceeded",v$="Maximum ASN.1 node count exceeded",S$="Maximum ASN.1 content length exceeded";function Vd(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:w$,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:b$,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:x$}}function A$(r){let e=new Rt({},Vt);return e.error=r,{offset:-1,result:e}}function I$(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return v$}function T$(r,e){if(r>e.maxContentLength)return S$}function f8(r,e,t,n){let o=n.depth+1;if(o>n.maxDepth)return A$(E$);n.depth=o;try{return jA(r,e,t,n)}finally{n.depth-=1}}function C$(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function jA(r,e=0,t=r.length,n=Vd()){let o=e,s=new Rt({},Vt),i=new Mo;if(!Ko(i,r,e,t))return s.error=i.error,{offset:-1,result:s};if(!r.subarray(e,e+t).length)return s.error="Zero buffer length",{offset:-1,result:s};let c=I$(n);if(c)return s.error=c,{offset:-1,result:s};let l=s.idBlock.fromBER(r,e,t);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),l===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=l,t-=s.idBlock.blockLength,l=s.lenBlock.fromBER(r,e,t),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),l===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};e=l,t-=s.lenBlock.blockLength;let u=s.lenBlock.isIndefiniteForm?t:s.lenBlock.length,d=T$(u,n);if(d)return s.error=d,{offset:-1,result:s};if(!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let f=Rt;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};f=J.EndOfContent;break;case 1:f=J.Boolean;break;case 2:f=J.Integer;break;case 3:f=J.BitString;break;case 4:f=J.OctetString;break;case 5:f=J.Null;break;case 6:f=J.ObjectIdentifier;break;case 10:f=J.Enumerated;break;case 12:f=J.Utf8String;break;case 13:f=J.RelativeObjectIdentifier;break;case 14:f=J.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:f=J.Sequence;break;case 17:f=J.Set;break;case 18:f=J.NumericString;break;case 19:f=J.PrintableString;break;case 20:f=J.TeletexString;break;case 21:f=J.VideotexString;break;case 22:f=J.IA5String;break;case 23:f=J.UTCTime;break;case 24:f=J.GeneralizedTime;break;case 25:f=J.GraphicString;break;case 26:f=J.VisibleString;break;case 27:f=J.GeneralString;break;case 28:f=J.UniversalString;break;case 29:f=J.CharacterString;break;case 30:f=J.BmpString;break;case 31:f=J.DATE;break;case 32:f=J.TimeOfDay;break;case 33:f=J.DateTime;break;case 34:f=J.Duration;break;default:{let h=s.idBlock.isConstructed?new J.Constructed:new J.Primitive;h.idBlock=s.idBlock,h.lenBlock=s.lenBlock,h.warnings=s.warnings,s=h}}break;default:f=s.idBlock.isConstructed?J.Constructed:J.Primitive}return s=C$(s,f),l=s.fromBER(r,e,u,n),s.valueBeforeDecodeView=r.subarray(o,o+s.blockLength),{offset:l,result:s}}function L0(r,e={}){if(!r.byteLength){let t=new Rt({},Vt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return jA(ve.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,Vd(e))}function k$(r,e){return r?1:e}var jn=class extends Vt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,o){let s=ve.BufferSourceConverter.toUint8Array(e),i=o??Vd();if(!Ko(this,s,t,n))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;k$(this.isIndefiniteForm,n)>0;){let c=f8(s,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Bd)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Bd?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new Od;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Xn:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};jn.NAME="ConstructedValueBlock";var YA,Ds=class extends Rt{constructor(e={}){super(e,jn),this.idBlock.isConstructed=!0}fromBER(e,t,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
46
46
|
`).map(o=>` ${o}`).join(`
|
|
47
47
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
48
48
|
${e.join(`
|
|
49
|
-
`)}`:`${t} :`}};YA=Ds;J.Constructed=YA;Ds.NAME="CONSTRUCTED";var J0=class extends Vt{fromBER(e,t,n){return t}toBER(e){return Xn}};J0.override="EndOfContentValueBlock";var XA,Z0=class extends Rt{constructor(e={}){super(e,J0),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};XA=Z0;J.EndOfContent=XA;Z0.NAME=Bd;var QA,oa=class extends Rt{constructor(e={}){super(e,Vt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};QA=oa;J.Null=QA;oa.NAME="NULL";var em=class extends Vo(Vt){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ve.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);return Ko(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,l8.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};em.NAME="BooleanValueBlock";var JA,tm=class extends Rt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,em),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};JA=tm;J.Boolean=JA;tm.NAME="BOOLEAN";var rm=class extends Vo(jn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,o){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=jn.prototype.fromBER.call(this,e,t,n,o),s===-1)return s;for(let i=0;i<this.value.length;i++){let a=this.value[i].constructor.NAME;if(a===Bd){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==qA)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?jn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};rm.NAME="OctetStringValueBlock";var h8,Uo=class extends Rt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},rm),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,o){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let a=o??Vd(),c=f8(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ds.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=ve.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof h8&&e.push(t.valueBlock.valueHexView);return ve.BufferSourceConverter.concat(e)}};h8=Uo;J.OctetString=h8;Uo.NAME=qA;var nm=class extends Vo(jn){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,o){if(!n)return t;let s=-1;if(this.isConstructed){if(s=jn.prototype.fromBER.call(this,e,t,n,o),s===-1)return s;for(let c of this.value){let l=c.constructor.NAME;if(l===Bd){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(l!==zA)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return s}let i=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,i,t,n))return-1;let a=i.subarray(t,t+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let l=o??Vd(),u=f8(c,0,c.byteLength,l);u.offset!==-1&&u.offset===n-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+n}toBER(e,t){if(this.isConstructed)return jn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let o=new Uint8Array(1);return o[0]=0,o.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};nm.NAME="BitStringValueBlock";var ZA,om=class extends Rt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},nm),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,o){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ds.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let i of t)e.push(i.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};ZA=om;J.BitString=ZA;om.NAME=zA;var eI;function _$(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,d=0;for(let f=u;f>=0;f--,d++)!0===d<a.length?l=s[i-d]+a[c-d]+t[0]:l=s[i-d]+t[0],t[0]=l/10,!0===d>=s.length?s=z0(new Uint8Array([l%10]),s):s[i-d]=l%10;return t[0]>0&&(s=z0(t,s)),s}function HA(r){if(r>=Rd.length)for(let e=Rd.length;e<=r;e++){let t=new Uint8Array([0]),n=Rd[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=z0(t,n)),Rd.push(n)}return Rd[r]}function P$(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let d=c;d>=0;d--,u++)l=s[i-u]-a[c-u]-t,!0===l<0?(t=1,s[i-u]=l+10):(t=0,s[i-u]=l);if(t>0)for(let d=i-c+1;d>=0;d--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var Md=class extends Vo(Vt){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=l8.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array($A(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++)(o&1)===1&&(n===e?(t=P$(HA(n),t),i="-"):t=_$(t,HA(n))),n++,o>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=VA.charAt(t[c]));return a===!1&&(i+=VA.charAt(0)),i}};eI=Md;Md.NAME="IntegerValueBlock";Object.defineProperty(eI.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Nd,Fo=class extends Rt{constructor(e={}){super(e,Md),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return W0(),BigInt(this.valueBlock.toString())}static fromBigInt(e){W0();let t=BigInt(e),n=new Od,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(ve.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${ve.Convert.ToHex(a)}`)+t,u=ve.BufferSourceConverter.toUint8Array(ve.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new Nd({valueHex:n.final()})}convertToDER(){let e=new Nd({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Nd({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Nd=Fo;J.Integer=Nd;Fo.NAME="INTEGER";var tI,sm=class extends Fo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};tI=sm;J.Enumerated=tI;sm.NAME="ENUMERATED";var Ud=class extends Vo(Vt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=na(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){W0();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Ls(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xn;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=ve.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Ud.NAME="sidBlock";var im=class extends Vt{constructor({value:e=Bc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Ud;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Xn;t.push(o)}return u8(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Ud;if(o>Number.MAX_SAFE_INTEGER){W0();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};im.NAME="ObjectIdentifierValueBlock";var rI,Yn=class extends Rt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,im),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};rI=Yn;J.ObjectIdentifier=rI;Yn.NAME="OBJECT IDENTIFIER";var Fd=class extends Vo(Mo){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=na(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Ls(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xn;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ve.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Fd.NAME="relativeSidBlock";var am=class extends Vt{constructor({value:e=Bc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Fd;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,Xn;n.push(s)}return u8(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Fd;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};am.NAME="RelativeObjectIdentifierValueBlock";var nI,cm=class extends Rt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,am),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};nI=cm;J.RelativeObjectIdentifier=nI;cm.NAME="RelativeObjectIdentifier";var oI,Sr=class extends Ds{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};oI=Sr;J.Sequence=oI;Sr.NAME="SEQUENCE";var sI,lm=class extends Ds{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};sI=lm;J.Set=sI;lm.NAME="SET";var um=class extends Vo(Vt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Bc}toJSON(){return{...super.toJSON(),value:this.value}}};um.NAME="StringValueBlock";var dm=class extends um{};dm.NAME="SimpleStringValueBlock";var hr=class extends Y0{constructor({...e}={}){super(e,dm)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ve.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};hr.NAME="SIMPLE STRING";var fm=class extends hr{fromBuffer(e){this.valueBlock.valueHexView=ve.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ve.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ve.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ve.Convert.FromUtf8String(e)),this.valueBlock.value=e}};fm.NAME="Utf8StringValueBlock";var iI,$o=class extends fm{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};iI=$o;J.Utf8String=iI;$o.NAME="UTF8String";var hm=class extends hr{fromBuffer(e){this.valueBlock.value=ve.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ve.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ve.Convert.FromUtf16String(e))}};hm.NAME="BmpStringValueBlock";var aI,pm=class extends hm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};aI=pm;J.BmpString=aI;pm.NAME="BMPString";var mm=class extends hr{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Ls(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};mm.NAME="UniversalStringValueBlock";var cI,gm=class extends mm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};cI=gm;J.UniversalString=cI;gm.NAME="UniversalString";var lI,ym=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};lI=ym;J.NumericString=lI;ym.NAME="NumericString";var uI,wm=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};uI=wm;J.PrintableString=uI;wm.NAME="PrintableString";var dI,bm=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};dI=bm;J.TeletexString=dI;bm.NAME="TeletexString";var fI,xm=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};fI=xm;J.VideotexString=fI;xm.NAME="VideotexString";var hI,Em=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};hI=Em;J.IA5String=hI;Em.NAME="IA5String";var pI,vm=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};pI=vm;J.GraphicString=pI;vm.NAME="GraphicString";var mI,$d=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};mI=$d;J.VisibleString=mI;$d.NAME="VisibleString";var gI,Sm=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};gI=Sm;J.GeneralString=gI;Sm.NAME="GeneralString";var yI,Am=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};yI=Am;J.CharacterString=yI;Am.NAME="CharacterString";var wI,Kd=class extends $d{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ve.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=vr(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=vr(this.month,2),t[2]=vr(this.day,2),t[3]=vr(this.hour,2),t[4]=vr(this.minute,2),t[5]=vr(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};wI=Kd;J.UTCTime=wI;Kd.NAME="UTCTime";var bI,Im=class extends Kd{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,f=n.indexOf("+"),h="";if(f===-1&&(f=n.indexOf("-"),d=-1),f!==-1){if(h=n.substring(f+1),n=n.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=d*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let d=new Number(`0${n.substring(l)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");s=d.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*s;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*s;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=1e3*s;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let d=1;d<u.length;d++)switch(d){case 1:this.year=parseInt(u[d],10);break;case 2:this.month=parseInt(u[d],10);break;case 3:this.day=parseInt(u[d],10);break;case 4:this.hour=parseInt(u[d],10)+a;break;case 5:this.minute=parseInt(u[d],10)+c;break;case 6:this.second=parseInt(u[d],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(vr(this.year,4)),t.push(vr(this.month,2)),t.push(vr(this.day,2)),t.push(vr(this.hour,2)),t.push(vr(this.minute,2)),t.push(vr(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(vr(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};bI=Im;J.GeneralizedTime=bI;Im.NAME="GeneralizedTime";var xI,Tm=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};xI=Tm;J.DATE=xI;Tm.NAME="DATE";var EI,Cm=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};EI=Cm;J.TimeOfDay=EI;Cm.NAME="TimeOfDay";var vI,km=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};vI=km;J.DateTime=vI;km.NAME="DateTime";var SI,_m=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};SI=_m;J.Duration=SI;_m.NAME="Duration";var AI,Pm=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};AI=Pm;J.TIME=AI;Pm.NAME="TIME";async function Dm(r,e){let n=await Nc.create().encrypt(r,e);return $e.encode(n)}async function p8(r,e,t){if(r.type==="RSA")return N$(r,e,t);if(r.type==="Ed25519")return L$(r,e,t);if(r.type==="secp256k1")return D$(r,e,t);if(r.type==="ECDSA")return R$(r,e,t);throw new cn}async function L$(r,e,t="libp2p-key"){if(t==="libp2p-key")return Dm(Gi(r),e);throw new A(`export format '${t}' is not supported`)}async function D$(r,e,t="libp2p-key"){if(t==="libp2p-key")return Dm(Gi(r),e);throw new A("Export format is not supported")}async function R$(r,e,t="libp2p-key"){if(t==="libp2p-key")return Dm(Gi(r),e);throw new A(`export format '${t}' is not supported`)}async function N$(r,e,t="pkcs-8"){if(t==="pkcs-8")return O$(r,e);if(t==="libp2p-key")return Dm(Gi(r),e);throw new A("Export format is not supported")}async function O$(r,e){let t=yt.get(),o=new Sr({value:[new Fo({value:0}),new Sr({value:[new Yn({value:"1.2.840.113549.1.1.1"}),new oa]}),new Uo({valueHex:r.raw})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=t.getRandomValues(new Uint8Array(16)),a=await K0(Hn,e,i,{c:1e4,dkLen:32}),c=t.getRandomValues(new Uint8Array(16)),l=await t.subtle.importKey("raw",ee(a),"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:ee(c)},l,ee(s)),d=new Sr({value:[new Uo({valueHex:i}),new Fo({value:1e4}),new Fo({value:32}),new Sr({value:[new Yn({value:"1.2.840.113549.2.11"}),new oa]})]}),f=new Sr({value:[new Yn({value:"1.2.840.113549.1.5.13"}),new Sr({value:[new Sr({value:[new Yn({value:"1.2.840.113549.1.5.12"}),d]}),new Sr({value:[new Yn({value:"2.16.840.1.101.3.4.1.42"}),new Uo({valueHex:c})]})]})]}),p=new Sr({value:[f,new Uo({valueHex:u})]}).toBER(),y=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...M(y,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
50
|
-
`)}async function m8(r,e){try{let t=await B$(r,e);return Xv(t)}catch{}if(!r.includes("BEGIN"))throw new A("Encrypted key was not a libp2p-key or a PEM file");return M$(r,e)}async function B$(r,e){let t=$e.decode(r);return Nc.create().decrypt(t,e)}async function M$(r,e){let t=yt.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Lm(s),{iv:a,salt:c,iterations:l,keySize:u,cipherText:d}=U$(i),f=await K0(Hn,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",ee(f),"AES-CBC",!1,["decrypt"]),p=Hd(await t.subtle.decrypt({name:"AES-CBC",iv:ee(a)},h,ee(d))),{result:y}=Lm(p);n=kI(y)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Lm(s);n=kI(i)}else throw new A("Could not parse private key from PEM data");let o=Qv(n);if(o.type!=="RSA")throw new A("Could not parse RSA private key from PEM data");return o}function U$(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new A("Only pkcs5PBES2 encrypted private keys are supported");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new A("Only pkcs5PBKDF2 key derivation functions are supported");let s=n.valueBlock.value[1],i=Hd(s.valueBlock.value[0].getValue()),a=1e4,c=32;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new A("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");let l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new A("Only AES-CBC encryption schemes are supported")}}}}let d=Hd(l.valueBlock.value[1].getValue());return{cipherText:Hd(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:d}}function kI(r){return Hd(r.valueBlock.value[2].getValue())}function Hd(r){return new Uint8Array(r,0,r.byteLength)}var F$="/pkcs8/",g8="/info/",qd=new WeakMap,sa={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function Mc(r){return r==null||typeof r!="string"?!1:r===(0,_I.default)(r.trim())&&r.length>0}async function Ht(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function ia(r){return new Me(F$+r)}function Uc(r){return new Me(g8+r)}async function $$(r){let e=Gi(r),t=await He.digest(e);return ge.encode(t.bytes).substring(1)}var Rm=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...a8,...t.dek}},this.self=t.selfKey??"self",this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<sa.minKeyLength)throw new Error(`dek.keyLength must be least ${sa.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<sa.minSaltLength)throw new Error(`dek.saltLength must be least ${sa.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<sa.minIterationCount)throw new Error(`dek.iterationCount must be least ${sa.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?Dd(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";qd.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[xe]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(sa.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=M(crypto.getRandomValues(new Uint8Array(t)),"base64")),e}static get options(){return{dek:{...a8}}}async findKeyByName(e){if(!Mc(e))throw await Ht(),new A(`Invalid key name '${e}'`);let t=Uc(e);try{let n=await this.components.datastore.get(t);return JSON.parse(M(n))}catch(n){throw await Ht(),this.log.error("could not read key from datastore - %e",n),new Te(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:g8};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(M(n.value));if(o.id===e)return o}throw new A(`Key with id '${e}' does not exist.`)}catch(t){throw await Ht(),t}}async importKey(e,t){if(!Mc(e))throw await Ht(),new A(`Invalid key name '${e}'`);if(t==null)throw await Ht(),new A("Key is required");let n=ia(e);if(await this.components.datastore.has(n))throw await Ht(),new A(`Key '${e}' already exists`);let s,i;try{s=await $$(t);let l=qd.get(this);if(l==null)throw new A("dek missing");let u=l.dek;i=await p8(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await Ht(),l}let a={name:e,id:s},c=this.components.datastore.batch();return c.put(n,O(i)),c.put(Uc(e),O(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!Mc(e))throw await Ht(),new A(`Invalid key name '${e}'`);let t=ia(e);try{let n=await this.components.datastore.get(t),o=M(n),s=qd.get(this);if(s==null)throw new A("dek missing");let i=s.dek;return await m8(o,i)}catch(n){throw await Ht(),n}}async removeKey(e){if(!Mc(e)||e===this.self)throw await Ht(),new A(`Invalid key name '${e}'`);let t=ia(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(Uc(e)),await o.commit(),n}async listKeys(){let e={prefix:g8},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(M(n.value)));return t}async renameKey(e,t){if(!Mc(e)||e===this.self)throw await Ht(),new A(`Invalid old key name '${e}'`);if(!Mc(t)||t===this.self)throw await Ht(),new A(`Invalid new key name '${t}'`);let n=ia(e),o=ia(t),s=Uc(e),i=Uc(t);if(await this.components.datastore.has(o))throw await Ht(),new A(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(M(l));u.name=t;let d=this.components.datastore.batch();return d.put(o,c),d.put(i,O(JSON.stringify(u))),d.delete(n),d.delete(s),await d.commit(),u}catch(c){throw await Ht(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await Ht(),new A(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await Ht(),new A(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await Ht(),new A(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=qd.get(this);if(n==null)throw new A("dek missing");let o=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?Dd(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";qd.set(this,{dek:s});let i=await this.listKeys();for(let a of i){let c=await this.components.datastore.get(ia(a.name)),l=M(c),u=await m8(l,o),d=s.toString(),f=await p8(u,d,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(ia(a.name),O(f)),h.put(Uc(a.name),O(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function PI(r={}){return e=>new Rm(e,r)}async function y8(r,e={}){let t=e.selfKey??"self",n=PI(e)({datastore:r,logger:tc()}),o;return await r.has(new Me(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await rp(e.keyType??"Ed25519"),await n.importKey(t,o)),o}function St(r=0){return new Uint8Array(r)}function er(r=0){return new Uint8Array(r)}var Fc=!!globalThis.process?.env?.DUMP_SESSION_KEYS,w8=16;function K$(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Nm(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function $c(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function At(r,e,t=""){let n=K$(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function b8(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function LI(r,e,t=!1){At(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!Kc(r))throw new Error("invalid output, must be aligned")}function Qn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function _n(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function V$(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var aa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,H$=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var q$=r=>{for(let e=0;e<r.length;e++)r[e]=H$(r[e]);return r},Ho=aa?r=>r:q$;function DI(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function RI(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function NI(r,e,t){let n=e,o=t||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(r),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var OI=(r,e)=>{function t(n,...o){if(At(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];At(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&At(o[1],void 0,"AAD");let i=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");At(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,At(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(At(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function zd(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(At(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!Kc(e))throw new Error("invalid output, must be aligned");return e}function BI(r,e,t){$c(r),$c(e),Nm(t);let n=new Uint8Array(16),o=V$(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function Kc(r){return r.byteOffset%4===0}function Vc(r){return Uint8Array.from(At(r))}var UI=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),z$=Ho(Qn(UI("expand 16-byte k"))),W$=Ho(Qn(UI("expand 32-byte k")));function Ae(r,e){return r<<e|r>>>32-e}var Wd=64,G$=16,x8=2**32-1,MI=Uint32Array.of();function j$(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(Wd),u=Qn(l),d=aa&&Kc(o)&&Kc(s),f=d?Qn(o):MI,h=d?Qn(s):MI;if(!aa){for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),Ho(u),i>=x8)throw new Error("arx: counter overflow");let y=Math.min(Wd,c-p);for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}return}for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),i>=x8)throw new Error("arx: counter overflow");let y=Math.min(Wd,c-p);if(d&&y===Wd){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,w;m<G$;m++)w=g+m,h[w]=f[w]^u[m];p+=Wd;continue}for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}}function FI(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=DI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return $c(o),$c(i),Nm(s),Nm(t),(a,c,l,u,d=0)=>{At(a,void 0,"key"),At(c,void 0,"nonce"),At(l,void 0,"data");let f=l.length;if(u=zd(f,u,!1),$c(d),d<0||d>=x8)throw new Error("arx: counter overflow");let h=[],p=a.length,y,g;if(p===32)h.push(y=Vc(a)),g=W$;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=z$,h.push(y);else throw At(a,32,"arx key"),new Error("invalid key size");(!aa||!Kc(c))&&h.push(c=Vc(c));let m=Qn(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let E=c.subarray(0,16);if(aa)n(g,m,Qn(E),m);else{let S=Ho(Uint32Array.from(g));n(S,m,Qn(E),m),_n(S),Ho(m)}c=c.subarray(16)}else aa||Ho(m);let w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let E=new Uint8Array(12);E.set(c,s?0:12-c.length),c=E,h.push(c)}let x=Ho(Qn(c));try{return j$(r,g,m,x,l,u,d,i),u}finally{_n(...h)}}}function qt(r,e){return r[e++]&255|(r[e++]&255)<<8}var E8=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Vc(At(e,32,"key"));let t=qt(e,0),n=qt(e,2),o=qt(e,4),s=qt(e,6),i=qt(e,8),a=qt(e,10),c=qt(e,12),l=qt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=qt(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],f=i[5],h=i[6],p=i[7],y=i[8],g=i[9],m=qt(e,t+0),w=qt(e,t+2),x=qt(e,t+4),E=qt(e,t+6),S=qt(e,t+8),T=qt(e,t+10),I=qt(e,t+12),C=qt(e,t+14),U=s[0]+(m&8191),j=s[1]+((m>>>13|w<<3)&8191),z=s[2]+((w>>>10|x<<6)&8191),v=s[3]+((x>>>7|E<<9)&8191),D=s[4]+((E>>>4|S<<12)&8191),L=s[5]+(S>>>1&8191),_=s[6]+((S>>>14|T<<2)&8191),k=s[7]+((T>>>11|I<<5)&8191),N=s[8]+((I>>>8|C<<8)&8191),F=s[9]+(C>>>5|o),P=0,$=P+U*a+j*(5*g)+z*(5*y)+v*(5*p)+D*(5*h);P=$>>>13,$&=8191,$+=L*(5*f)+_*(5*d)+k*(5*u)+N*(5*l)+F*(5*c),P+=$>>>13,$&=8191;let H=P+U*c+j*a+z*(5*g)+v*(5*y)+D*(5*p);P=H>>>13,H&=8191,H+=L*(5*h)+_*(5*f)+k*(5*d)+N*(5*u)+F*(5*l),P+=H>>>13,H&=8191;let Z=P+U*l+j*c+z*a+v*(5*g)+D*(5*y);P=Z>>>13,Z&=8191,Z+=L*(5*p)+_*(5*h)+k*(5*f)+N*(5*d)+F*(5*u),P+=Z>>>13,Z&=8191;let fe=P+U*u+j*l+z*c+v*a+D*(5*g);P=fe>>>13,fe&=8191,fe+=L*(5*y)+_*(5*p)+k*(5*h)+N*(5*f)+F*(5*d),P+=fe>>>13,fe&=8191;let ue=P+U*d+j*u+z*l+v*c+D*a;P=ue>>>13,ue&=8191,ue+=L*(5*g)+_*(5*y)+k*(5*p)+N*(5*h)+F*(5*f),P+=ue>>>13,ue&=8191;let Ne=P+U*f+j*d+z*u+v*l+D*c;P=Ne>>>13,Ne&=8191,Ne+=L*a+_*(5*g)+k*(5*y)+N*(5*p)+F*(5*h),P+=Ne>>>13,Ne&=8191;let Oe=P+U*h+j*f+z*d+v*u+D*l;P=Oe>>>13,Oe&=8191,Oe+=L*c+_*a+k*(5*g)+N*(5*y)+F*(5*p),P+=Oe>>>13,Oe&=8191;let Be=P+U*p+j*h+z*f+v*d+D*u;P=Be>>>13,Be&=8191,Be+=L*l+_*c+k*a+N*(5*g)+F*(5*y),P+=Be>>>13,Be&=8191;let Ie=P+U*y+j*p+z*h+v*f+D*d;P=Ie>>>13,Ie&=8191,Ie+=L*u+_*l+k*c+N*a+F*(5*g),P+=Ie>>>13,Ie&=8191;let Je=P+U*g+j*y+z*p+v*h+D*f;P=Je>>>13,Je&=8191,Je+=L*d+_*u+k*l+N*c+F*a,P+=Je>>>13,Je&=8191,P=(P<<2)+P|0,P=P+$|0,$=P&8191,P=P>>>13,H+=P,s[0]=$,s[1]=H,s[2]=Z,s[3]=fe,s[4]=ue,s[5]=Ne,s[6]=Oe,s[7]=Be,s[8]=Ie,s[9]=Je}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;_n(n)}update(e){b8(this),At(e),e=Vc(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,_n(this.h,this.r,this.buffer,this.pad)}digestInto(e){b8(this),LI(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},$I=NI(32,r=>new E8(r));function Y$(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],f=e[2],h=e[3],p=e[4],y=e[5],g=e[6],m=e[7],w=o,x=t[0],E=t[1],S=t[2],T=i,I=a,C=c,U=l,j=u,z=d,v=f,D=h,L=p,_=y,k=g,N=m,F=w,P=x,$=E,H=S;for(let fe=0;fe<s;fe+=2)T=T+j|0,F=Ae(F^T,16),L=L+F|0,j=Ae(j^L,12),T=T+j|0,F=Ae(F^T,8),L=L+F|0,j=Ae(j^L,7),I=I+z|0,P=Ae(P^I,16),_=_+P|0,z=Ae(z^_,12),I=I+z|0,P=Ae(P^I,8),_=_+P|0,z=Ae(z^_,7),C=C+v|0,$=Ae($^C,16),k=k+$|0,v=Ae(v^k,12),C=C+v|0,$=Ae($^C,8),k=k+$|0,v=Ae(v^k,7),U=U+D|0,H=Ae(H^U,16),N=N+H|0,D=Ae(D^N,12),U=U+D|0,H=Ae(H^U,8),N=N+H|0,D=Ae(D^N,7),T=T+z|0,H=Ae(H^T,16),k=k+H|0,z=Ae(z^k,12),T=T+z|0,H=Ae(H^T,8),k=k+H|0,z=Ae(z^k,7),I=I+v|0,F=Ae(F^I,16),N=N+F|0,v=Ae(v^N,12),I=I+v|0,F=Ae(F^I,8),N=N+F|0,v=Ae(v^N,7),C=C+D|0,P=Ae(P^C,16),L=L+P|0,D=Ae(D^L,12),C=C+D|0,P=Ae(P^C,8),L=L+P|0,D=Ae(D^L,7),U=U+j|0,$=Ae($^U,16),_=_+$|0,j=Ae(j^_,12),U=U+j|0,$=Ae($^U,8),_=_+$|0,j=Ae(j^_,7);let Z=0;n[Z++]=i+T|0,n[Z++]=a+I|0,n[Z++]=c+C|0,n[Z++]=l+U|0,n[Z++]=u+j|0,n[Z++]=d+z|0,n[Z++]=f+v|0,n[Z++]=h+D|0,n[Z++]=p+L|0,n[Z++]=y+_|0,n[Z++]=g+k|0,n[Z++]=m+N|0,n[Z++]=w+F|0,n[Z++]=x+P|0,n[Z++]=E+$|0,n[Z++]=S+H|0}var X$=FI(Y$,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Q$=new Uint8Array(16),KI=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(Q$.subarray(t))},J$=new Uint8Array(32);function VI(r,e,t,n,o){o!==void 0&&At(o,void 0,"AAD");let s=r(e,t,J$),i=BI(n.length,o?o.length:0,!0),a=$I.create(s);o&&KI(a,o),KI(a,n),a.update(i);let c=a.digest();return _n(s,i),c}var Z$=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=zd(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=VI(r,e,t,c,n);return i.set(l,a),_n(l),i},decrypt(s,i){i=zd(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=VI(r,e,t,a,n);if(!RI(c,l))throw _n(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),_n(l),i}}),v8=OI({blockSize:64,nonceLength:12,tagLength:16},Z$(X$));function qI(r,e,t){return Ao(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Wi(r,t,e)}var S8=Uint8Array.of(0),HI=Uint8Array.of();function zI(r,e,t,n=32){Ao(r),xr(n,"length"),Ut(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=HI:Ut(t,void 0,"info");let i=new Uint8Array(s*o),a=Wi.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)S8[0]=u+1,c.update(u===0?HI:l).update(t).update(S8).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Qt(l,S8),i.slice(0,n)}var A8={hashSHA256(r){return Zr(r.subarray())},getHKDF(r,e){let t=qI(Zr,e,r),o=zI(Zr,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=Qu.utils.randomSecretKey();return{publicKey:Qu.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Qu.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Qu.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return v8(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return v8(n,e,t).decrypt(r.subarray(),o)}};var WI=A8;function GI(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var Hc=r=>{let e=er(2);return e[0]=r>>8,e[1]=r,e};Hc.bytes=2;var qc=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};qc.bytes=2;function jI(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var _8={};V(_8,{base10:()=>iK});var X3e=new Uint8Array(0);function YI(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 qo(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function XI(r){return new TextEncoder().encode(r)}function QI(r){return new TextDecoder().decode(r)}function eK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,y++;for(var x=(w-m)*u+1>>>0,E=new Uint8Array(x);m!==w;){for(var S=p[m],T=0,I=x-1;(S!==0||T<g)&&I!==-1;I--,T++)S+=256*E[I]>>>0,E[I]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");g=T,m++}for(var C=x-g;C!==x&&E[C]===0;)C++;for(var U=c.repeat(y);C<x;++C)U+=r.charAt(E[C]);return U}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var w=(p.length-y)*l+1>>>0,x=new Uint8Array(w);p[y];){var E=t[p.charCodeAt(y)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<m)&&T!==-1;T--,S++)E+=a*x[T]>>>0,x[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");m=S,y++}if(p[y]!==" "){for(var I=w-m;I!==w&&x[I]===0;)I++;for(var C=new Uint8Array(g+(w-I)),U=g;I!==w;)C[U++]=x[I++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var tK=eK,rK=tK,ZI=rK;var I8=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")}},T8=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return eT(this,e)}},C8=class{decoders;constructor(e){this.decoders=e}or(e){return eT(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 eT(r,e){return new C8({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var k8=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new I8(e,t,n),this.decoder=new T8(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zc({name:r,prefix:e,encode:t,decode:n}){return new k8(r,e,t,n)}function Rs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=ZI(t,r);return zc({prefix:e,name:r,encode:n,decode:s=>qo(o(s))})}function nK(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function oK(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function sK(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ct({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=sK(n);return zc({prefix:e,name:r,encode(s){return oK(s,n,t)},decode(s){return nK(s,o,t,r)}})}var iK=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var P8={};V(P8,{base16:()=>aK,base16upper:()=>cK});var aK=ct({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cK=ct({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var L8={};V(L8,{base2:()=>lK});var lK=ct({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var D8={};V(D8,{base256emoji:()=>pK});var tT=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}"),uK=tT.reduce((r,e,t)=>(r[t]=e,r),[]),dK=tT.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function fK(r){return r.reduce((e,t)=>(e+=uK[t],e),"")}function hK(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=dK[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var pK=zc({prefix:"\u{1F680}",name:"base256emoji",encode:fK,decode:hK});var R8={};V(R8,{base32:()=>Wc,base32hex:()=>wK,base32hexpad:()=>xK,base32hexpadupper:()=>EK,base32hexupper:()=>bK,base32pad:()=>gK,base32padupper:()=>yK,base32upper:()=>mK,base32z:()=>vK});var Wc=ct({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mK=ct({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gK=ct({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yK=ct({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wK=ct({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bK=ct({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xK=ct({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),EK=ct({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vK=ct({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var N8={};V(N8,{base36:()=>Gd,base36upper:()=>SK});var Gd=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),SK=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var O8={};V(O8,{base58btc:()=>Jn,base58flickr:()=>AK});var Jn=Rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),AK=Rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var B8={};V(B8,{base64:()=>IK,base64pad:()=>TK,base64url:()=>CK,base64urlpad:()=>kK});var IK=ct({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),TK=ct({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CK=ct({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kK=ct({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var M8={};V(M8,{base8:()=>_K});var _K=ct({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var U8={};V(U8,{identity:()=>PK});var PK=zc({prefix:"\0",name:"identity",encode:r=>QI(r),decode:r=>XI(r)});var f4e=new TextEncoder,h4e=new TextDecoder;var $8={};V($8,{identity:()=>ZK});var RK=oT,rT=128,NK=127,OK=~NK,BK=Math.pow(2,31);function oT(r,e,t){e=e||[],t=t||0;for(var n=t;r>=BK;)e[t++]=r&255|rT,r/=128;for(;r&OK;)e[t++]=r&255|rT,r>>>=7;return e[t]=r|0,oT.bytes=t-n+1,e}var MK=F8,UK=128,nT=127;function F8(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw F8.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&nT)<<o:(i&nT)*Math.pow(2,o),o+=7}while(i>=UK);return F8.bytes=s-n,t}var FK=Math.pow(2,7),$K=Math.pow(2,14),KK=Math.pow(2,21),VK=Math.pow(2,28),HK=Math.pow(2,35),qK=Math.pow(2,42),zK=Math.pow(2,49),WK=Math.pow(2,56),GK=Math.pow(2,63),jK=function(r){return r<FK?1:r<$K?2:r<KK?3:r<VK?4:r<HK?5:r<qK?6:r<zK?7:r<WK?8:r<GK?9:10},YK={encode:RK,decode:MK,encodingLength:jK},XK=YK,jd=XK;function Yd(r,e=0){return[jd.decode(r,e),jd.decode.bytes]}function Gc(r,e,t=0){return jd.encode(r,e,t),e}function jc(r){return jd.encodingLength(r)}function Xc(r,e){let t=e.byteLength,n=jc(r),o=n+jc(t),s=new Uint8Array(o+t);return Gc(r,s,0),Gc(t,s,n),s.set(e,o),new Yc(r,t,e,s)}function sT(r){let e=qo(r),[t,n]=Yd(e),[o,s]=Yd(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Yc(t,o,i,e)}function iT(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&YI(r.bytes,t.bytes)}}var Yc=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var aT=0,QK="identity",cT=qo;function JK(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 Xc(aT,cT(r))}var ZK={code:aT,name:QK,encode:cT,digest:JK};var H8={};V(H8,{sha256:()=>tV,sha512:()=>rV});var eV=20;function V8({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new K8(r,e,t,n,o)}var K8=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??eV,this.maxDigestLength=s}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?lT(n,this.code,t?.truncate):n.then(o=>lT(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function lT(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 Xc(e,r)}function dT(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var tV=V8({name:"sha2-256",code:18,encode:dT("SHA-256")}),rV=V8({name:"sha2-512",code:19,encode:dT("SHA-512")});function fT(r,e){let{bytes:t,version:n}=r;return n===0?oV(t,q8(r),e??Jn.encoder):sV(t,q8(r),e??Wc.encoder)}var hT=new WeakMap;function q8(r){let e=hT.get(r);if(e==null){let t=new Map;return hT.set(r,t),t}return e}var Bm=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Qd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==iV)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=Xc(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&&iT(e.multihash,n.multihash)}toString(e){return fT(this,e)}toJSON(){return{"/":fT(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??pT(n,o,s.bytes))}else if(t[aV]===!0){let{version:n,multihash:o,code:s}=t,i=sT(o);return r.create(n,s,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!==Qd)throw new Error(`Version 0 CID must use dag-pb (code: ${Qd}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=pT(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Qd,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=qo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Yc(t.multihashCode,t.digestSize,s,o);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]=Yd(e.subarray(t));return t+=f,d},o=n(),s=Qd;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=nV(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return q8(s).set(n,e),s}};function nV(r,e){switch(r[0]){case"Q":{let t=e??Jn;return[Jn.prefix,t.decode(`${Jn.prefix}${r}`)]}case Jn.prefix:{let t=e??Jn;return[Jn.prefix,t.decode(r)]}case Wc.prefix:{let t=e??Wc;return[Wc.prefix,t.decode(r)]}case Gd.prefix:{let t=e??Gd;return[Gd.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 oV(r,e,t){let{prefix:n}=t;if(n!==Jn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function sV(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Qd=112,iV=18;function pT(r,e,t){let n=jc(r),o=n+jc(e),s=new Uint8Array(o+t.byteLength);return Gc(r,s,0),Gc(e,s,n),s.set(t,o),s}var aV=Symbol.for("@ipld/js-cid/CID");var z8={...U8,...L8,...M8,..._8,...P8,...R8,...N8,...O8,...B8,...D8},O4e={...H8,...$8};function gT(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var mT=gT("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),W8=gT("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=er(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),cV={utf8:mT,"utf-8":mT,hex:z8.base16,latin1:W8,ascii:W8,binary:W8,...z8},Mm=cV;function Zn(r,e="utf8"){let t=Mm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function G8(r,e){!e.enabled||!Fc||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${Zn(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${Zn(r.privateKey,"hex")}`)):e("Missing local static keys."))}function j8(r,e){!e.enabled||!Fc||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Zn(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Zn(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function yT(r,e){!e.enabled||!Fc||e(r?`REMOTE_STATIC_PUBLIC_KEY ${Zn(r.subarray(),"hex")}`:"Missing remote static public key.")}function Y8(r,e){!e.enabled||!Fc||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Zn(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function X8(r,e,t){!t.enabled||!Fc||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&Zn(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&Zn(e.k,"hex")}`))}function Qc(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=er(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Q8(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 bT=Symbol.for("@achingbrain/uint8arraylist");function wT(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Um(r){return!!r?.[bT]}var eo=class r{bufs;length;[bT]=!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(Um(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Um(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=wT(this.bufs,e);return t.buf[t.index]}set(e,t){let n=wT(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(Um(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Qc(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Qc(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(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(!Um(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;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=er(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=St(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=St(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=St(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=er(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=St(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=St(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=St(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=St(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=St(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q8(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function ca(r,e="utf8"){let t=Mm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Jc=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var uV=0,dV=4294967295,fV="Cipherstate has reached maximum n, a new handshake must be performed",Fm=class{n;bytes;view;constructor(e=uV){this.n=e,this.bytes=St(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>dV)throw new Error(fV)}};var la=St(0),Zc=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Fm(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},J8=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=ca(t,"utf-8");this.h=hV(e,n),this.ck=this.h,this.cs=new Zc(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Zc(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new eo(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,la);return[new Zc(this.crypto,e),new Zc(this.crypto,t)]}},Z8=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new J8(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Jd=class extends Z8{writeMessageA(e){return new eo(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new eo(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new eo(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Jc(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new Jc(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new Jc(`handshake stage 2 validation fail: ${t.message}`)}}};function hV(r,e){if(e.length<=32){let t=St(32);return t.set(e),t}else return r.hash(e)}var pV=Math.pow(2,7),mV=Math.pow(2,14),gV=Math.pow(2,21),xT=Math.pow(2,28),ET=Math.pow(2,35),vT=Math.pow(2,42),ST=Math.pow(2,49),pr=128,Ns=127;function Zd(r){if(r<pV)return 1;if(r<mV)return 2;if(r<gV)return 3;if(r<xT)return 4;if(r<ET)return 5;if(r<vT)return 6;if(r<ST)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function AT(r,e,t=0){switch(Zd(r)){case 8:e[t++]=r&255|pr,r/=128;case 7:e[t++]=r&255|pr,r/=128;case 6:e[t++]=r&255|pr,r/=128;case 5:e[t++]=r&255|pr,r/=128;case 4:e[t++]=r&255|pr,r>>>=7;case 3:e[t++]=r&255|pr,r>>>=7;case 2:e[t++]=r&255|pr,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function IT(r,e){let t=r[e],n=0;if(n+=t&Ns,t<pr||(t=r[e+1],n+=(t&Ns)<<7,t<pr)||(t=r[e+2],n+=(t&Ns)<<14,t<pr)||(t=r[e+3],n+=(t&Ns)<<21,t<pr)||(t=r[e+4],n+=(t&Ns)*xT,t<pr)||(t=r[e+5],n+=(t&Ns)*ET,t<pr)||(t=r[e+6],n+=(t&Ns)*vT,t<pr)||(t=r[e+7],n+=(t&Ns)*ST,t<pr))return n;throw new RangeError("Could not decode varint")}var e5=new Float32Array([-0]),Os=new Uint8Array(e5.buffer);function TT(r,e,t){e5[0]=r,e[t]=Os[0],e[t+1]=Os[1],e[t+2]=Os[2],e[t+3]=Os[3]}function CT(r,e){return Os[0]=r[e],Os[1]=r[e+1],Os[2]=r[e+2],Os[3]=r[e+3],e5[0]}var t5=new Float64Array([-0]),tr=new Uint8Array(t5.buffer);function kT(r,e,t){t5[0]=r,e[t]=tr[0],e[t+1]=tr[1],e[t+2]=tr[2],e[t+3]=tr[3],e[t+4]=tr[4],e[t+5]=tr[5],e[t+6]=tr[6],e[t+7]=tr[7]}function _T(r,e){return tr[0]=r[e],tr[1]=r[e+1],tr[2]=r[e+2],tr[3]=r[e+3],tr[4]=r[e+4],tr[5]=r[e+5],tr[6]=r[e+6],tr[7]=r[e+7],t5[0]}var yV=BigInt(Number.MAX_SAFE_INTEGER),wV=BigInt(Number.MIN_SAFE_INTEGER),Wr=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 ua;if(e<yV&&e>wV)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>PT&&(o=0n,++n>PT&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ua;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ua}},ua=new Wr(0,0);ua.toBigInt=function(){return 0n};ua.zzEncode=ua.zzDecode=function(){return this};ua.length=function(){return 1};var PT=4294967296n;function LT(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 DT(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function r5(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Pn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function $m(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var n5=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Pn(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 Pn(this,4);return $m(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Pn(this,4);return $m(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Pn(this,4);let e=CT(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Pn(this,4);let e=_T(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 Pn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return DT(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Pn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Pn(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 Wr(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 Pn(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 Pn(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 Pn(this,8);let e=$m(this.buf,this.pos+=4),t=$m(this.buf,this.pos+=4);return new Wr(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=IT(this.buf,this.pos);return this.pos+=Zd(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 o5(r){return new n5(r instanceof Uint8Array?r:r.subarray())}function Km(r,e,t){let n=o5(r);return e.decode(n,void 0,t)}function s5(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return er(i);o+i>e&&(n=er(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var da=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function i5(){}var c5=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},bV=s5();function xV(r){return globalThis.Buffer!=null?er(r):bV(r)}var tf=class{len;head;tail;states;constructor(){this.len=0,this.head=new da(i5,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new da(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new l5((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(Vm,10,Wr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Wr.fromBigInt(e);return this._push(Vm,t.length(),t)}uint64Number(e){return this._push(AT,Zd(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=Wr.fromBigInt(e).zzEncode();return this._push(Vm,t.length(),t)}sint64Number(e){let t=Wr.fromNumber(e).zzEncode();return this._push(Vm,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(a5,1,e?1:0)}fixed32(e){return this._push(ef,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Wr.fromBigInt(e);return this._push(ef,4,t.lo)._push(ef,4,t.hi)}fixed64Number(e){let t=Wr.fromNumber(e);return this._push(ef,4,t.lo)._push(ef,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(TT,4,e)}double(e){return this._push(kT,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(a5,1,0):this.uint32(t)._push(vV,t,e)}string(e){let t=LT(e);return t!==0?this.uint32(t)._push(r5,t,e):this._push(a5,1,0)}fork(){return this.states=new c5(this),this.head=this.tail=new da(i5,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 da(i5,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=xV(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function a5(r,e,t){e[t]=r&255}function EV(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var l5=class extends da{next;constructor(e,t){super(EV,e,t),this.next=void 0}};function Vm(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 ef(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 vV(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(tf.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(SV,e,r),this},tf.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(AV,e,r),this});function SV(r,e,t){e.set(r,t)}function AV(r,e,t){r.length<40?r5(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(ca(r),t)}function u5(){return new tf}function Hm(r,e){let t=u5();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var rf;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(rf||(rf={}));function d5(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function qm(r,e){return d5("message",rf.LENGTH_DELIMITED,r,e)}var nf=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var zm;(function(r){let e;r.codec=()=>(e==null&&(e=qm((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new nf('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new nf('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Hm(t,r.codec()),r.decode=(t,n)=>Km(t,r.codec(),n)})(zm||(zm={}));var of;(function(r){let e;r.codec=()=>(e==null&&(e=qm((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),zm.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:St(0),identitySig:St(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=zm.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Hm(t,r.codec()),r.decode=(t,n)=>Km(t,r.codec(),n)})(of||(of={}));async function h5(r,e,t){let n=await r.sign(OT(e));return of.encode({identityKey:Lt(r.publicKey),identitySig:n,extensions:t})}async function p5(r,e,t){try{let n=of.decode(r),o=Et(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=OT(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new lh(n.message)}}function OT(r){let e=ca("noise-libp2p-static-key:");return r instanceof Uint8Array?Qc([e,r],e.length+r.length):(r.prepend(e),r)}var f5=class extends cs{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new c1({lengthDecoder:qc,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new eo;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(Hc(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new eo;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-w8<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-w8);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function m5(r,e,t){return new f5(r,e,t)}async function BT(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await h5(s,a.publicKey,l),d=new Jd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});G8(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(la),e),t.trace("Stage 0 - Initiator finished sending first message."),j8(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Y8(d.re,t),yT(d.rs,t),t.trace("Initiator going to check remote's signature...");let h=await p5(f,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,y]=d.ss.split();return X8(p,y,t),{payload:h,encrypt:g=>p.encryptWithAd(la,g),decrypt:(g,m)=>y.decryptWithAd(la,g,m)}}async function MT(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await h5(s,a.publicKey,l),d=new Jd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});G8(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Y8(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),j8(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let h=await p5(f,d.rs,c),[p,y]=d.ss.split();return X8(p,y,t),{payload:h,encrypt:g=>y.encryptWithAd(la,g),decrypt:(g,m)=>p.decryptWithAd(la,g,m)}}var Wm=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??WI;this.crypto=GI(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?jI(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??St(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[xe]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=fs(e,{lengthEncoder:Hc,lengthDecoder:qc,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Et(s.payload.identityKey);return{connection:m5(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Wn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new uh("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=fs(e,{lengthEncoder:Hc,lengthDecoder:qc,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Et(s.payload.identityKey);return{connection:m5(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Wn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await BT({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await MT({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function Gm(r={}){return e=>new Wm(e,r)}function zo(r=0){return new Uint8Array(r)}function af(r=0){return new Uint8Array(r)}function g5(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=af(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function UT(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 $T=Symbol.for("@achingbrain/uint8arraylist");function FT(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function jm(r){return!!r?.[$T]}var el=class r{bufs;length;[$T]=!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(jm(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(jm(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=FT(this.bufs,e);return t.buf[t.index]}set(e,t){let n=FT(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(jm(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return g5(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:g5(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(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(!jm(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;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=af(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=zo(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=zo(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=zo(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=af(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=zo(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=zo(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=zo(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=zo(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=zo(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!UT(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var nt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(nt||(nt={}));var ke;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(ke||(ke={}));var Yye=Object.values(ke).filter(r=>typeof r!="string"),KT=0,It;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(It||(It={}));var to=12;var Wo=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function VT(r){return r?.reason!==null}var Gr=class extends Wo{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,It.ProtocolError),this.name="InvalidFrameError"}},tl=class extends Wo{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,It.ProtocolError),this.name="UnRequestedPingError"}},rl=class extends Wo{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,It.ProtocolError),this.name="NotMatchingPingError"}};var Ym=class extends Wo{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,It.ProtocolError),this.name="StreamAlreadyExistsError"}},Xm=class extends Wo{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,It.ProtocolError),this.name="DecodeInvalidVersionError"}},Qm=class extends Wo{static name="BothClientsError";constructor(e="Both clients"){super(e,It.ProtocolError),this.name="BothClientsError"}},nl=class extends Wo{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,It.ProtocolError),this.name="ReceiveWindowExceededError"}};var e8e=new Set([Gr.name,tl.name,rl.name,Ym.name,Xm.name,Qm.name,nl.name]),cf=256*1024,Jm=16*1024*1024;var lf={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:cf,maxStreamWindowSize:Jm,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function HT(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new A("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new A("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new A("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new A("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<cf)throw new A("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new A("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new A("MaxStreamWindowSize must be less than equal MAX_UINT32")}function zT(r){return r.header.type===nt.Data&&r.data!==null}var qT=2**24;function IV(r){if(r[0]!==KT)throw new Gr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*qT+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*qT+(r[9]<<16)+(r[10]<<8)+r[11]}}var Zm=class{buffer;constructor(){this.buffer=new el}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=to;if(this.buffer.byteLength<to)return;let t=IV(this.buffer.subarray(0,to));if(t.type===nt.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(to,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function y5(r){let e=new Uint8Array(to);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var mr;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(mr||(mr={}));var e2=class extends ds{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??cf;super({...e,maxMessageSize:t-to}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??Jm,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=mr.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let s=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,s);e.consume(s);let c=this.sendFrame({type:nt.Data,flag:i,streamID:this.streamId,length:s},a);if(this.sendWindowCapacity-=s,n+=s,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:nt.WindowUpdate,flag:ke.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|ke.FIN;this.sendFrame({type:nt.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=mr.Paused}sendResume(){this.state=mr.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-to,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!zT(e))throw new Gr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new nl("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&ke.ACK)===ke.ACK&&this.state===mr.SYNSent&&(this.state=mr.Established),(e&ke.FIN)===ke.FIN&&this.onRemoteCloseWrite(),(e&ke.RST)===ke.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case mr.Init:return this.state=mr.SYNSent,ke.SYN;case mr.SYNReceived:return this.state=mr.Established,ke.ACK;default:return 0}}sendWindowUpdate(){if(this.state===mr.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:nt.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function WT(r){return{type:nt[r.type],flags:[(r.flag&ke.SYN)===ke.SYN?"SYN":void 0,(r.flag&ke.ACK)===ke.ACK?"ACK":void 0,(r.flag&ke.FIN)===ke.FIN?"FIN":void 0,(r.flag&ke.RST)===ke.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var GT="/yamux/1.0.0",t2=class{protocol=GT;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[xe]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new w5(e,{...this._init})}},w5=class extends us{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:GT,name:"yamux"}),this.client=e.direction==="outbound",HT(t),this.enableKeepAlive=t.enableKeepAlive??lf.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??lf.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??lf.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??lf.maxOutboundStreams,this.decoder=new Zm,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=oc(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new an("Muxer closed remotely");if(this.localGoAway!==void 0)throw new an("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Sa("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,mr.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new an("Muxer closed remotely");if(this.localGoAway!==void 0)throw new an("Muxer closed locally");if(this.activePing!=null)return Ue(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await Ue(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??It.NormalTermination;this.log.trace("muxer close reason=%s",It[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=It.InternalError;VT(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(s=>s.streamId===e)!=null)throw new A("Stream already exists with that id");let o=new e2({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",WT(e.header)),t===0)switch(n){case nt.Ping:{this.handlePing(e.header);return}case nt.GoAway:{this.handleGoAway(o);return}default:throw new Gr("Invalid frame type")}else switch(e.header.type){case nt.Data:case nt.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new Gr("Invalid frame type")}}handlePing(e){if(e.flag===ke.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,ke.ACK);else if(e.flag===ke.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new Gr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new tl("ping not requested");if(this.activePing.id!==e)throw new rl("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",It[e]??"unknown"),this.remoteGoAway=e,e===It.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&ke.SYN)===ke.SYN&&this.incomingStream(t);let s=this.streams.find(i=>i.streamId===t);if(s===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case nt.WindowUpdate:{s.handleWindowUpdate(e);return}case nt.Data:{s.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new A("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:nt.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:nt.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}let t=this._newStream(e,mr.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===nt.Data){if(t==null)throw new Gr("Invalid frame");n=new el(y5(e),t)}else n=y5(e);return this.log.trace("sending frame %o",WT(e)),this.send(n)}sendPing(e,t=ke.SYN){t===ke.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:nt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=It.NormalTermination){this.log("sending GoAway reason=%s",It[e]),this.localGoAway=e,this.sendFrame({type:nt.GoAway,flag:0,streamID:0,length:e})}};function jT(r={}){return()=>new t2(r)}var YT="libp2p",XT="autonat",QT="1.0.0";var Qe;(function(r){let e;(function(f){f.DIAL="DIAL",f.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(f){f[f.DIAL=0]="DIAL",f[f.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(f){f.codec=()=>et(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(f){f.OK="OK",f.E_DIAL_ERROR="E_DIAL_ERROR",f.E_DIAL_REFUSED="E_DIAL_REFUSED",f.E_BAD_REQUEST="E_BAD_REQUEST",f.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(f){f[f.OK=0]="OK",f[f.E_DIAL_ERROR=100]="E_DIAL_ERROR",f[f.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",f[f.E_BAD_REQUEST=200]="E_BAD_REQUEST",f[f.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(f){f.codec=()=>et(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(f){let h;f.codec=()=>(h==null&&(h=ae((m,w,x={})=>{if(x.lengthDelimited!==!1&&w.fork(),m.id!=null&&(w.uint32(10),w.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let E of m.addrs)w.uint32(18),w.bytes(E);x.lengthDelimited!==!1&&w.ldelim()},(m,w,x={})=>{let E={addrs:[]},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{E.id=m.bytes();break}case 2:{if(x.limits?.addrs!=null&&E.addrs.length===x.limits.addrs)throw new he('Decode error - repeated field "addrs" had too many elements');E.addrs.push(m.bytes());break}default:{m.skipType(T&7);break}}}return E},function*(m,w,x,E={}){let S={addrs:0},T=w==null?m.len:m.pos+w;for(;m.pos<T;){let I=m.uint32();switch(I>>>3){case 1:{yield{field:`${x}.id`,value:m.bytes()};break}case 2:{if(E.limits?.addrs!=null&&S.addrs===E.limits.addrs)throw new he('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${x}.addrs[]`,index:S.addrs,value:m.bytes()},S.addrs++;break}default:{m.skipType(I&7);break}}}})),h);function p(m){return se(m,f.codec())}f.encode=p;function y(m,w){return oe(m,f.codec(),w)}f.decode=y;function g(m,w){return ie(m,f.codec(),w)}f.stream=g})(s=r.PeerInfo||(r.PeerInfo={}));let i;(function(f){let h;f.codec=()=>(h==null&&(h=ae((m,w,x={})=>{x.lengthDelimited!==!1&&w.fork(),m.peer!=null&&(w.uint32(10),r.PeerInfo.codec().encode(m.peer,w)),x.lengthDelimited!==!1&&w.ldelim()},(m,w,x={})=>{let E={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?E.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:x.limits?.peer}):m.skipType(T&7)}return E},function*(m,w,x,E={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${x}.peer`,{limits:E.limits?.peer}):m.skipType(T&7)}})),h);function p(m){return se(m,f.codec())}f.encode=p;function y(m,w){return oe(m,f.codec(),w)}f.decode=y;function g(m,w){return ie(m,f.codec(),w)}f.stream=g})(i=r.Dial||(r.Dial={}));let a;(function(f){let h;f.codec=()=>(h==null&&(h=ae((m,w,x={})=>{x.lengthDelimited!==!1&&w.fork(),m.status!=null&&(w.uint32(8),r.ResponseStatus.codec().encode(m.status,w)),m.statusText!=null&&(w.uint32(18),w.string(m.statusText)),m.addr!=null&&(w.uint32(26),w.bytes(m.addr)),x.lengthDelimited!==!1&&w.ldelim()},(m,w,x={})=>{let E={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{E.status=r.ResponseStatus.codec().decode(m);break}case 2:{E.statusText=m.string();break}case 3:{E.addr=m.bytes();break}default:{m.skipType(T&7);break}}}return E},function*(m,w,x,E={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{yield{field:`${x}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${x}.statusText`,value:m.string()};break}case 3:{yield{field:`${x}.addr`,value:m.bytes()};break}default:{m.skipType(T&7);break}}}})),h);function p(m){return se(m,f.codec())}f.encode=p;function y(m,w){return oe(m,f.codec(),w)}f.decode=y;function g(m,w){return ie(m,f.codec(),w)}f.stream=g})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.type!=null&&(h.uint32(8),r.MessageType.codec().encode(f.type,h)),f.dial!=null&&(h.uint32(18),r.Dial.codec().encode(f.dial,h)),f.dialResponse!=null&&(h.uint32(26),r.DialResponse.codec().encode(f.dialResponse,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.type=r.MessageType.codec().decode(f);break}case 2:{y.dial=r.Dial.codec().decode(f,f.uint32(),{limits:p.limits?.dial});break}case 3:{y.dialResponse=r.DialResponse.codec().decode(f,f.uint32(),{limits:p.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.type`,value:r.MessageType.codec().decode(f)};break}case 2:{yield*r.Dial.codec().stream(f,f.uint32(),`${p}.dial`,{limits:y.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(f,f.uint32(),`${p}.dialResponse`,{limits:y.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return se(f,r.codec())}r.encode=l;function u(f,h){return oe(f,r.codec(),h)}r.decode=u;function d(f,h){return ie(f,r.codec(),h)}r.stream=d})(Qe||(Qe={}));var LV=4,DV=8,r2=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??YT}/${XT}/${QT}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=gt({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=oc(this.findRandomPeers.bind(this),6e4),this.addressFilter=Nt(1024)}[Symbol.toStringTag]="@libp2p/autonat";[xe]=["@libp2p/autonat"];get[kr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=de([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=We(e,{maxDataLength:this.maxMessageSize}).pb(Qe),s=await o.read({signal:n}),i=await this.handleAutonatMessage(s,t,{signal:n});await o.write(i,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>ce(d).host),s=e.dial;if(s==null)return this.log.error("dial was missing from message"),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let i,a=s.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=Ee(a.id);i=wt(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",i),!t.remotePeer.equals(i))return this.log("target peer %p did not equal sending peer %p",i,t.remotePeer),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>G(d)).filter(d=>{try{let f=ce(d);return it(d)?!1:f.host!==ce(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(f.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(f=>f.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${i.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",i),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),i);let l="",u=c[0];for(let d of c){let f;u=d;try{if(f=await this.components.connectionManager.openConnection(d,n),!f.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,f.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",i,d),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.OK,addr:f.remoteAddr.decapsulateCode(421).bytes}}}catch(h){this.log.error("could not dial %p - %e",i,h),l=h.message}finally{f!=null&&await f.close()}}return{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,s)=>o.type==="observed"&&s.type!=="observed"?1:s.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||ce(o.multiaddr).type==="ip6"&&(!t||!Bh(o.multiaddr))||it(o.multiaddr)));for(let o of n){let s=o.multiaddr.toString(),i=this.dialResults.get(s);if(i!=null){if(i.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",i.multiaddr,e);continue}if(i.queue.size>10){this.log.trace("%a already has enough peers queued",i.multiaddr);continue}}if(i==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(s),this.addressFilter.has(s))continue;this.addressFilter.add(s),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",s),i={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:cy(),queue:new Xt({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(s,i)}return i}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:i})=>ce(i).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),s=this.getFirstUnverifiedMultiaddr(o,n);if(s==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){s.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s.multiaddr),this.confirmAddress(s)):this.log("skipping verifying %a because we are too close to the connection limit",s.multiaddr);return}s.queue.add(async i=>{await this.askPeerToVerify(e,o,i)},{peerId:e.remotePeer,multiaddr:s.multiaddr}).catch(i=>{s?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,s?.multiaddr,i)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let s=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let i=await e.newStream(this.protocol,{signal:s});try{let a=We(i).pb(Qe),[,c]=await Promise.all([a.write({type:Qe.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:s}),a.read({signal:s})]);if(c.type!==Qe.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Qe.ResponseStatus.OK&&l!==Qe.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Qe.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Qe.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===LV&&this.confirmAddress(o),o.failure===DV&&this.unconfirmAddress(o)}finally{try{await i.close({signal:s})}catch(a){i.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=ce(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new A(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function JT(r={}){return e=>new r2(e,r)}var RV="bootstrap",NV=50,OV=1e3,b5=class extends le{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??OV,this.list=t.list.map(n=>G(n)).filter(n=>Ha.matches(n)?n.getComponents().findLast(s=>s.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:Xe(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[ii]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[xe]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??RV]:{value:this._init.tagValue??NV,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function ZT(r){return e=>new b5(e,r)}var x5=1e3,eC=60*x5;var e5e=120*eC,tC=1,n2=5e3,rC=100;var uf=`${ci}-circuit-relay`,t5e=2*eC,r5e=BigInt(1<<17),fa="/libp2p/circuit/relay/0.2.0/hop",E5="/libp2p/circuit/relay/0.2.0/stop",n5e=30*x5,o5e=30*x5,v5=300,nC=4096,oC=.001;var Us;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>et(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Bs.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),df.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Ms.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),Tt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Bs.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=df.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Ms.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=Tt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Bs.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*df.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Ms.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:Tt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Us||(Us={}));var ro;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>et(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Bs.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Ms.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),Tt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Bs.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Ms.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=Tt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Bs.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Ms.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:Tt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(ro||(ro={}));var Bs;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.id!=null&&s.id.byteLength>0&&(i.uint32(10),i.bytes(s.id)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={id:me(0),addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.id=s.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new he('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:s.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new he('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Bs||(Bs={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.expire!=null&&s.expire!==0n&&(i.uint32(8),i.uint64(s.expire)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);s.voucher!=null&&(i.uint32(26),hf.codec().encode(s.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.expire=s.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new he('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 3:{c.voucher=hf.codec().decode(s,s.uint32(),{limits:a.limits?.voucher});break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.expire`,value:s.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new he('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}case 3:{yield*hf.codec().stream(s,s.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(df||(df={}));var Ms;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.duration!=null&&(i.uint32(8),i.uint32(s.duration)),s.data!=null&&(i.uint32(16),i.uint64(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.duration=s.uint32();break}case 2:{c.data=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:s.uint32()};break}case 2:{yield{field:`${a}.data`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Ms||(Ms={}));var Tt;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Tt||(Tt={}));var S5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(S5||(S5={}));(function(r){r.codec=()=>et(S5)})(Tt||(Tt={}));var ff;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.relay!=null&&s.relay.byteLength>0&&(i.uint32(10),i.bytes(s.relay)),s.peer!=null&&s.peer.byteLength>0&&(i.uint32(18),i.bytes(s.peer)),s.expiration!=null&&s.expiration!==0n&&(i.uint32(24),i.uint64(s.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={relay:me(0),peer:me(0),expiration:0n},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.relay=s.bytes();break}case 2:{c.peer=s.bytes();break}case 3:{c.expiration=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:s.bytes()};break}case 2:{yield{field:`${a}.peer`,value:s.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(ff||(ff={}));var hf;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&(i.uint32(26),ff.codec().encode(s.payload,i)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:me(0),payloadType:me(0),signature:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=ff.codec().decode(s,s.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield*ff.codec().stream(s,s.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(hf||(hf={}));var pf=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},o2=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},s2=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function A5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var mf=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},i2=Re(Se(Ha.matchers[0],De(290))),a2=Re(De(290));var c2=class extends le{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(fa,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(fa)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=sC(n),i=sC(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Xt({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=de([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function sC(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(M(e)).getTime()}var I5=class extends le{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??n2,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(a2.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(i2.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new si(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>G(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function iC(r){return new I5(r)}var aC="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var cC=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=aC[t[r]&63];return e};var BV=60*1e3*10,MV=60*1e3*5,UV=30*1e3,l2=class extends le{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Jt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??rC,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??n2,this.started=!1,this.relayFilter=Nt(100),this.reserveQueue=new Xt({concurrency:t?.reservationConcurrency??tC,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(uf)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[uf]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=cC();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new si("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new s2("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new si("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let p=this.connectionManager.getConnections(e),y=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(g=>g.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),y=!0),y&&A5(s.reservation.expire)>BV)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new pf("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(_t.matches(a.remoteAddr))throw new o2("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=A5(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-MV,UV),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new pf("Made reservation on relay but did not need any more discovered relays");f={timeout:d,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[uf]:{value:1,ttl:l}}}),this.#r();let h={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(fa,t),s=We(n).pb(Us);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Us.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===Tt.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=G(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=G(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>G(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[uf]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Nt(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var T5=class extends ls{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function C5(r){return new T5(r)}var FV=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(G)}catch{return!1}return!0},lC={maxInboundStopStreams:v5,maxOutboundStopStreams:v5,stopTimeout:3e4},u2=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??lC.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??lC.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new c2(e,{filter:t.discoveryFilter??ly(nC,oC)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new l2(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[xe]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[kr](){return this.discovery!=null?["@libp2p/identify"]:[]}[ts]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(E5,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await ht(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ct(this.discovery,this.reservationStore),await this.components.registrar.unhandle(E5),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=G(n[0]),s=G(n[n.length-1]),i=o.getComponents().find(h=>h.code===421)?.value,a=s.getComponents().find(h=>h.code===421)?.value;if(i==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new Zo(`C${h}`)}let c=Xe(i),l=Xe(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new R("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new R("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new R("circuit-relay:open-hop-stream")),f=await d.newStream(fa,t);let h=We(f).pb(Us);t.onProgress?.(new R("circuit-relay:write-connect-message")),await h.write({type:Us.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[G(s).bytes]}},t),t.onProgress?.(new R("circuit-relay:read-connect-response"));let p=await h.read(t);if(p.status!==Tt.OK)throw new pe(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new mf(p.limit),g=C5({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:y.onData,onDataWrite:y.onData,log:f.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(g,{...t,limits:y.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,p.limit??"none",d.id),m}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,h),f?.abort(h),h}}createListener(e){return iC({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>i2.exactMatch(t)||a2.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>_t.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=We(e).pb(ro),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==ro.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!FV(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=wt(Ee(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.OK},{signal:n});let a=new mf(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=C5({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function uC(r={}){return e=>new u2(e,r)}var Ln;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>et(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new he('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new he('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(h&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Ln||(Ln={}));function k5(r,e){return _t.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:Xh.matches(r)?!0:B9.matches(r)?!it(r):!1}var dC=1024*4,fC=100,d2={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},f2=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??d2.timeout,this.retries=t.retries??d2.retries,this.maxInboundStreams=t.maxInboundStreams??d2.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??d2.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[kr]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(gf,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{_t.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(gf,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(gf),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([gf],{signal:o.signal,runOnLimitedConnection:!0});let s=We(t,{maxDataLength:dC}).pb(Ln);this.log("B sending connect to %p",e.remotePeer);let i=Date.now();await s.write({type:Ln.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await s.read(o);if(a.type!==Ln.Type.CONNECT)throw this.log("A sent wrong message type"),new pe("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new pe("DCUtR connect message had no multiaddrs");let l=Date.now()-i;this.log("A sending sync, rtt %dms",l),await s.write({type:Ln.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await hE(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:fC,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(s){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let s=o.multiaddr;return s.getComponents().find(i=>i.code===421)?.value==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(o=>k5(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(_t.exactMatch(s.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close({signal:o}),!0}catch(s){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,s)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=We(e,{maxDataLength:dC}).pb(Ln);this.log("A receiving connect");let s=await o.read(n);if(s.type!==Ln.Type.CONNECT)throw this.log("B sent wrong message type"),new pe("DCUtR message type was incorrect");if(s.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new pe("DCUtR connect message had no multiaddrs");let i=this.getDialableMultiaddrs(s.observedAddresses);if(i.length===0)throw this.log("B had no dialable multiaddrs in %o",s.observedAddresses.map(l=>G(l))),new pe("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:Ln.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==Ln.Type.SYNC)throw new pe("DCUtR message type was incorrect");this.log("A dialing",i);let c=await this.connectionManager.openConnection(i,{signal:n.signal,priority:fC,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=G(n);if(!k5(o,this.transportManager))continue;t.push(o)}catch{}return t}};var gf="/libp2p/dcutr";function hC(r={}){return e=>new f2(e,r)}var R5={};V(R5,{base10:()=>WV});var C7e=new Uint8Array(0);function pC(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 Go(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function mC(r){return new TextEncoder().encode(r)}function gC(r){return new TextDecoder().decode(r)}function $V(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,y++;for(var x=(w-m)*u+1>>>0,E=new Uint8Array(x);m!==w;){for(var S=p[m],T=0,I=x-1;(S!==0||T<g)&&I!==-1;I--,T++)S+=256*E[I]>>>0,E[I]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");g=T,m++}for(var C=x-g;C!==x&&E[C]===0;)C++;for(var U=c.repeat(y);C<x;++C)U+=r.charAt(E[C]);return U}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var w=(p.length-y)*l+1>>>0,x=new Uint8Array(w);p[y];){var E=t[p.charCodeAt(y)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<m)&&T!==-1;T--,S++)E+=a*x[T]>>>0,x[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");m=S,y++}if(p[y]!==" "){for(var I=w-m;I!==w&&x[I]===0;)I++;for(var C=new Uint8Array(g+(w-I)),U=g;I!==w;)C[U++]=x[I++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var KV=$V,VV=KV,wC=VV;var _5=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")}},P5=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bC(this,e)}},L5=class{decoders;constructor(e){this.decoders=e}or(e){return bC(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 bC(r,e){return new L5({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var D5=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new _5(e,t,n),this.decoder=new P5(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ol({name:r,prefix:e,encode:t,decode:n}){return new D5(r,e,t,n)}function Fs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=wC(t,r);return ol({prefix:e,name:r,encode:n,decode:s=>Go(o(s))})}function HV(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function qV(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function zV(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function lt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=zV(n);return ol({prefix:e,name:r,encode(s){return qV(s,n,t)},decode(s){return HV(s,o,t,r)}})}var WV=Fs({prefix:"9",name:"base10",alphabet:"0123456789"});var N5={};V(N5,{base16:()=>GV,base16upper:()=>jV});var GV=lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),jV=lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var O5={};V(O5,{base2:()=>YV});var YV=lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var B5={};V(B5,{base256emoji:()=>eH});var xC=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}"),XV=xC.reduce((r,e,t)=>(r[t]=e,r),[]),QV=xC.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function JV(r){return r.reduce((e,t)=>(e+=XV[t],e),"")}function ZV(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=QV[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var eH=ol({prefix:"\u{1F680}",name:"base256emoji",encode:JV,decode:ZV});var M5={};V(M5,{base32:()=>sl,base32hex:()=>oH,base32hexpad:()=>iH,base32hexpadupper:()=>aH,base32hexupper:()=>sH,base32pad:()=>rH,base32padupper:()=>nH,base32upper:()=>tH,base32z:()=>cH});var sl=lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tH=lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rH=lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nH=lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),oH=lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sH=lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),iH=lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),aH=lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cH=lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var U5={};V(U5,{base36:()=>yf,base36upper:()=>lH});var yf=Fs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lH=Fs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var F5={};V(F5,{base58btc:()=>no,base58flickr:()=>uH});var no=Fs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uH=Fs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $5={};V($5,{base64:()=>dH,base64pad:()=>fH,base64url:()=>hH,base64urlpad:()=>pH});var dH=lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fH=lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hH=lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pH=lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var K5={};V(K5,{base8:()=>mH});var mH=lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var V5={};V(V5,{identity:()=>gH});var gH=ol({prefix:"\0",name:"identity",encode:r=>gC(r),decode:r=>mC(r)});var H7e=new TextEncoder,q7e=new TextDecoder;var q5={};V(q5,{identity:()=>FH});var bH=SC,EC=128,xH=127,EH=~xH,vH=Math.pow(2,31);function SC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vH;)e[t++]=r&255|EC,r/=128;for(;r&EH;)e[t++]=r&255|EC,r>>>=7;return e[t]=r|0,SC.bytes=t-n+1,e}var SH=H5,AH=128,vC=127;function H5(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw H5.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&vC)<<o:(i&vC)*Math.pow(2,o),o+=7}while(i>=AH);return H5.bytes=s-n,t}var IH=Math.pow(2,7),TH=Math.pow(2,14),CH=Math.pow(2,21),kH=Math.pow(2,28),_H=Math.pow(2,35),PH=Math.pow(2,42),LH=Math.pow(2,49),DH=Math.pow(2,56),RH=Math.pow(2,63),NH=function(r){return r<IH?1:r<TH?2:r<CH?3:r<kH?4:r<_H?5:r<PH?6:r<LH?7:r<DH?8:r<RH?9:10},OH={encode:bH,decode:SH,encodingLength:NH},BH=OH,wf=BH;function bf(r,e=0){return[wf.decode(r,e),wf.decode.bytes]}function il(r,e,t=0){return wf.encode(r,e,t),e}function al(r){return wf.encodingLength(r)}function ll(r,e){let t=e.byteLength,n=al(r),o=n+al(t),s=new Uint8Array(o+t);return il(r,s,0),il(t,s,n),s.set(e,o),new cl(r,t,e,s)}function AC(r){let e=Go(r),[t,n]=bf(e),[o,s]=bf(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cl(t,o,i,e)}function IC(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pC(r.bytes,t.bytes)}}var cl=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var TC=0,MH="identity",CC=Go;function UH(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 ll(TC,CC(r))}var FH={code:TC,name:MH,encode:CC,digest:UH};var G5={};V(G5,{sha256:()=>KH,sha512:()=>VH});var $H=20;function W5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new z5(r,e,t,n,o)}var z5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??$H,this.maxDigestLength=s}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?kC(n,this.code,t?.truncate):n.then(o=>kC(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function kC(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 ll(e,r)}function PC(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var KH=W5({name:"sha2-256",code:18,encode:PC("SHA-256")}),VH=W5({name:"sha2-512",code:19,encode:PC("SHA-512")});function LC(r,e){let{bytes:t,version:n}=r;return n===0?qH(t,j5(r),e??no.encoder):zH(t,j5(r),e??sl.encoder)}var DC=new WeakMap;function j5(r){let e=DC.get(r);if(e==null){let t=new Map;return DC.set(r,t),t}return e}var p2=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ef)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==WH)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=ll(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&&IC(e.multihash,n.multihash)}toString(e){return LC(this,e)}toJSON(){return{"/":LC(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??RC(n,o,s.bytes))}else if(t[GH]===!0){let{version:n,multihash:o,code:s}=t,i=AC(o);return r.create(n,s,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!==Ef)throw new Error(`Version 0 CID must use dag-pb (code: ${Ef}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=RC(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ef,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Go(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new cl(t.multihashCode,t.digestSize,s,o);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]=bf(e.subarray(t));return t+=f,d},o=n(),s=Ef;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=HH(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return j5(s).set(n,e),s}};function HH(r,e){switch(r[0]){case"Q":{let t=e??no;return[no.prefix,t.decode(`${no.prefix}${r}`)]}case no.prefix:{let t=e??no;return[no.prefix,t.decode(r)]}case sl.prefix:{let t=e??sl;return[sl.prefix,t.decode(r)]}case yf.prefix:{let t=e??yf;return[yf.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 qH(r,e,t){let{prefix:n}=t;if(n!==no.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function zH(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ef=112,WH=18;function RC(r,e,t){let n=al(r),o=n+al(e),s=new Uint8Array(o+t.byteLength);return il(r,s,0),il(e,s,n),s.set(t,o),s}var GH=Symbol.for("@ipld/js-cid/CID");var Y5={...V5,...O5,...K5,...R5,...N5,...M5,...U5,...F5,...$5,...B5},fwe={...G5,...q5};function NC(r=0){return new Uint8Array(r)}function BC(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var OC=BC("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),X5=BC("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=NC(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jH={utf8:OC,"utf-8":OC,hex:Y5.base16,latin1:X5,ascii:X5,binary:X5,...Y5},MC=jH;function Q5(r,e="utf8"){let t=MC[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Q(r){if(r!==void 0&&r!==Q.REQUEST&&r!==Q.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");r===void 0||this.initialize(r),this.maxHeaderSize=Q.maxHeaderSize}Q.prototype.initialize=function(r,e){if(r!==Q.REQUEST&&r!==Q.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");this.type=r,this.state=r+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1};Q.encoding="ascii";Q.maxHeaderSize=80*1024;Q.REQUEST="REQUEST";Q.RESPONSE="RESPONSE";var UC=Q.kOnHeaders=1,J5=Q.kOnHeadersComplete=2,m2=Q.kOnBody=3,Z5=Q.kOnMessageComplete=4;Q.prototype[UC]=Q.prototype[J5]=Q.prototype[m2]=Q.prototype[Z5]=function(){};var FC=!0;Object.defineProperty(Q,"kOnExecute",{get:function(){return FC=!1,99}});var $C=Q.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK","SOURCE"],KC=$C.indexOf("CONNECT");Q.prototype.reinitialize=Q;Q.prototype.close=Q.prototype.pause=Q.prototype.resume=Q.prototype.remove=Q.prototype.free=function(){};Q.prototype._compatMode0_11=!1;Q.prototype.getAsyncId=function(){return 0};var YH={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};Q.prototype.execute=function(r,e,t){if(!(this instanceof Q))throw new TypeError("not a HTTPParser");e=e||0,t=typeof t=="number"?t:r.length,this.chunk=r,this.offset=e;var n=this.end=e+t;try{for(;this.offset<n&&!this[this.state](););}catch(o){if(this.isUserCall)throw o;return this.hadError=!0,o}return this.chunk=null,t=this.offset-e,YH[this.state]&&(this.headerSize+=t,this.headerSize>(this.maxHeaderSize||Q.maxHeaderSize))?new Error("max header size exceeded"):t};var XH={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};Q.prototype.finish=function(){if(!this.hadError){if(!XH[this.state])return new Error("invalid state for EOF");this.state==="BODY_RAW"&&this.userCall()(this[Z5]())}};Q.prototype.consume=Q.prototype.unconsume=Q.prototype.getCurrentBuffer=function(){};Q.prototype.userCall=function(){this.isUserCall=!0;var r=this;return function(e){return r.isUserCall=!1,e}};Q.prototype.nextRequest=function(){this.userCall()(this[Z5]()),this.reinitialize(this.type)};Q.prototype.consumeLine=function(){for(var r=this.end,e=this.chunk,t=this.offset;t<r;t++)if(e[t]===10){var n=this.line+Q5(e.subarray(this.offset,t),Q.encoding);return n.charAt(n.length-1)==="\r"&&(n=n.substr(0,n.length-1)),this.line="",this.offset=t+1,n}this.line+=Q5(e.subarray(this.offset,this.end),Q.encoding),this.offset=this.end};var QH=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,JH=/^[ \t]+(.*[^ \t])/;Q.prototype.parseHeader=function(r,e){if(r.indexOf("\r")!==-1)throw g2("HPE_LF_EXPECTED");var t=QH.exec(r),n=t&&t[1];if(n)e.push(n),e.push(t[2]);else{var o=JH.exec(r);o&&e.length&&(e[e.length-1]&&(e[e.length-1]+=" "),e[e.length-1]+=o[1])}};var ZH=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;Q.prototype.REQUEST_LINE=function(){var r=this.consumeLine();if(r){var e=ZH.exec(r);if(e===null)throw g2("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?e[1]:$C.indexOf(e[1]),this.info.method===-1)throw new Error("invalid request method");this.info.url=e[2],this.info.versionMajor=+e[3],this.info.versionMinor=+e[4],this.body_bytes=0,this.state="HEADER"}};var eq=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;Q.prototype.RESPONSE_LINE=function(){var r=this.consumeLine();if(r){var e=eq.exec(r);if(e===null)throw g2("HPE_INVALID_CONSTANT");this.info.versionMajor=+e[1],this.info.versionMinor=+e[2];var t=this.info.statusCode=+e[3];this.info.statusMessage=e[4],((t/100|0)===1||t===204||t===304)&&(this.body_bytes=0),this.state="HEADER"}};Q.prototype.shouldKeepAlive=function(){if(this.info.versionMajor>0&&this.info.versionMinor>0){if(this.connection.indexOf("close")!==-1)return!1}else if(this.connection.indexOf("keep-alive")===-1)return!1;return!!(this.body_bytes!==null||this.isChunked)};Q.prototype.HEADER=function(){var r=this.consumeLine();if(r!==void 0){var e=this.info;if(r)this.parseHeader(r,e.headers);else{for(var t=e.headers,n=!1,o,s=!1,i=0;i<t.length;i+=2)switch(t[i].toLowerCase()){case"transfer-encoding":this.isChunked=t[i+1].toLowerCase()==="chunked";break;case"content-length":if(o=+t[i+1],n){if(o!==this.body_bytes)throw g2("HPE_UNEXPECTED_CONTENT_LENGTH")}else n=!0,this.body_bytes=o;break;case"connection":this.connection+=t[i+1].toLowerCase();break;case"upgrade":s=!0;break}this.isChunked&&n&&(n=!1,this.body_bytes=null),s&&this.connection.indexOf("upgrade")!=-1?e.upgrade=this.type===Q.REQUEST||e.statusCode===101:e.upgrade=e.method===KC,this.isChunked&&e.upgrade&&(this.isChunked=!1),e.shouldKeepAlive=this.shouldKeepAlive();var a;if(FC?a=this.userCall()(this[J5](e)):a=this.userCall()(this[J5](e.versionMajor,e.versionMinor,e.headers,e.method,e.url,e.statusCode,e.statusMessage,e.upgrade,e.shouldKeepAlive)),a===2)return this.nextRequest(),!0;if(this.isChunked&&!a)this.state="BODY_CHUNKHEAD";else{if(a||this.body_bytes===0)return this.nextRequest(),e.upgrade;this.body_bytes===null?this.state="BODY_RAW":this.state="BODY_SIZED"}}}};Q.prototype.BODY_CHUNKHEAD=function(){var r=this.consumeLine();r!==void 0&&(this.body_bytes=parseInt(r,16),this.body_bytes?this.state="BODY_CHUNK":this.state="BODY_CHUNKTRAILERS")};Q.prototype.BODY_CHUNK=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[m2](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")};Q.prototype.BODY_CHUNKEMPTYLINE=function(){var r=this.consumeLine();if(r!==void 0){if(r!=="")throw new Error("Expected empty line");this.state="BODY_CHUNKHEAD"}};Q.prototype.BODY_CHUNKTRAILERS=function(){var r=this.consumeLine();r!==void 0&&(r?this.parseHeader(r,this.trailers):(this.trailers.length&&this.userCall()(this[UC](this.trailers,"")),this.nextRequest()))};Q.prototype.BODY_RAW=function(){this.userCall()(this[m2](this.chunk.slice(this.offset,this.end),0,this.end-this.offset)),this.offset=this.end};Q.prototype.BODY_SIZED=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[m2](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||this.nextRequest()};["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(r){var e=Q["kOn"+r];Object.defineProperty(Q.prototype,"on"+r,{get:function(){return this[e]},set:function(t){return this._compatMode0_11=!0,KC="CONNECT",this[e]=t}})});function g2(r){var e=new Error("Parse Error");return e.code=r,e}function VC(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function e7(r,e={}){let t=VC(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:s,done:i}=await t.next();if(this._cancelled)return;if(i===!0){o.close();return}o.enqueue(s)}catch(s){o.error(s)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var tq=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),HC=jl({name:"sha-1",code:17,encode:tq("SHA-1")});var s7={};V(s7,{base10:()=>cq});var Cwe=new Uint8Array(0);function qC(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 jo(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function zC(r){return new TextEncoder().encode(r)}function WC(r){return new TextDecoder().decode(r)}function rq(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,y++;for(var x=(w-m)*u+1>>>0,E=new Uint8Array(x);m!==w;){for(var S=p[m],T=0,I=x-1;(S!==0||T<g)&&I!==-1;I--,T++)S+=256*E[I]>>>0,E[I]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");g=T,m++}for(var C=x-g;C!==x&&E[C]===0;)C++;for(var U=c.repeat(y);C<x;++C)U+=r.charAt(E[C]);return U}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var w=(p.length-y)*l+1>>>0,x=new Uint8Array(w);p[y];){var E=t[p.charCodeAt(y)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<m)&&T!==-1;T--,S++)E+=a*x[T]>>>0,x[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");m=S,y++}if(p[y]!==" "){for(var I=w-m;I!==w&&x[I]===0;)I++;for(var C=new Uint8Array(g+(w-I)),U=g;I!==w;)C[U++]=x[I++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var nq=rq,oq=nq,jC=oq;var t7=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")}},r7=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return YC(this,e)}},n7=class{decoders;constructor(e){this.decoders=e}or(e){return YC(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 YC(r,e){return new n7({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var o7=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new t7(e,t,n),this.decoder=new r7(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ul({name:r,prefix:e,encode:t,decode:n}){return new o7(r,e,t,n)}function $s({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=jC(t,r);return ul({prefix:e,name:r,encode:n,decode:s=>jo(o(s))})}function sq(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function iq(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function aq(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ut({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=aq(n);return ul({prefix:e,name:r,encode(s){return iq(s,n,t)},decode(s){return sq(s,o,t,r)}})}var cq=$s({prefix:"9",name:"base10",alphabet:"0123456789"});var i7={};V(i7,{base16:()=>lq,base16upper:()=>uq});var lq=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),uq=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var a7={};V(a7,{base2:()=>dq});var dq=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var c7={};V(c7,{base256emoji:()=>gq});var XC=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}"),fq=XC.reduce((r,e,t)=>(r[t]=e,r),[]),hq=XC.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function pq(r){return r.reduce((e,t)=>(e+=fq[t],e),"")}function mq(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=hq[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var gq=ul({prefix:"\u{1F680}",name:"base256emoji",encode:pq,decode:mq});var l7={};V(l7,{base32:()=>dl,base32hex:()=>xq,base32hexpad:()=>vq,base32hexpadupper:()=>Sq,base32hexupper:()=>Eq,base32pad:()=>wq,base32padupper:()=>bq,base32upper:()=>yq,base32z:()=>Aq});var dl=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yq=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wq=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bq=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xq=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eq=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),vq=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sq=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Aq=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var u7={};V(u7,{base36:()=>vf,base36upper:()=>Iq});var vf=$s({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iq=$s({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var d7={};V(d7,{base58btc:()=>oo,base58flickr:()=>Tq});var oo=$s({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tq=$s({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var f7={};V(f7,{base64:()=>Cq,base64pad:()=>kq,base64url:()=>_q,base64urlpad:()=>Pq});var Cq=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kq=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_q=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Pq=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var h7={};V(h7,{base8:()=>Lq});var Lq=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var p7={};V(p7,{identity:()=>Dq});var Dq=ul({prefix:"\0",name:"identity",encode:r=>WC(r),decode:r=>zC(r)});var Hwe=new TextEncoder,qwe=new TextDecoder;var g7={};V(g7,{identity:()=>tz});var Oq=ZC,QC=128,Bq=127,Mq=~Bq,Uq=Math.pow(2,31);function ZC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Uq;)e[t++]=r&255|QC,r/=128;for(;r&Mq;)e[t++]=r&255|QC,r>>>=7;return e[t]=r|0,ZC.bytes=t-n+1,e}var Fq=m7,$q=128,JC=127;function m7(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw m7.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&JC)<<o:(i&JC)*Math.pow(2,o),o+=7}while(i>=$q);return m7.bytes=s-n,t}var Kq=Math.pow(2,7),Vq=Math.pow(2,14),Hq=Math.pow(2,21),qq=Math.pow(2,28),zq=Math.pow(2,35),Wq=Math.pow(2,42),Gq=Math.pow(2,49),jq=Math.pow(2,56),Yq=Math.pow(2,63),Xq=function(r){return r<Kq?1:r<Vq?2:r<Hq?3:r<qq?4:r<zq?5:r<Wq?6:r<Gq?7:r<jq?8:r<Yq?9:10},Qq={encode:Oq,decode:Fq,encodingLength:Xq},Jq=Qq,Sf=Jq;function Af(r,e=0){return[Sf.decode(r,e),Sf.decode.bytes]}function fl(r,e,t=0){return Sf.encode(r,e,t),e}function hl(r){return Sf.encodingLength(r)}function ml(r,e){let t=e.byteLength,n=hl(r),o=n+hl(t),s=new Uint8Array(o+t);return fl(r,s,0),fl(t,s,n),s.set(e,o),new pl(r,t,e,s)}function ek(r){let e=jo(r),[t,n]=Af(e),[o,s]=Af(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new pl(t,o,i,e)}function tk(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&qC(r.bytes,t.bytes)}}var pl=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var rk=0,Zq="identity",nk=jo;function ez(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 ml(rk,nk(r))}var tz={code:rk,name:Zq,encode:nk,digest:ez};var b7={};V(b7,{sha256:()=>nz,sha512:()=>oz});var rz=20;function w7({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new y7(r,e,t,n,o)}var y7=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??rz,this.maxDigestLength=s}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?ok(n,this.code,t?.truncate):n.then(o=>ok(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ok(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 ml(e,r)}function ik(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var nz=w7({name:"sha2-256",code:18,encode:ik("SHA-256")}),oz=w7({name:"sha2-512",code:19,encode:ik("SHA-512")});function ak(r,e){let{bytes:t,version:n}=r;return n===0?iz(t,x7(r),e??oo.encoder):az(t,x7(r),e??dl.encoder)}var ck=new WeakMap;function x7(r){let e=ck.get(r);if(e==null){let t=new Map;return ck.set(r,t),t}return e}var w2=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Tf)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==cz)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=ml(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&&tk(e.multihash,n.multihash)}toString(e){return ak(this,e)}toJSON(){return{"/":ak(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??lk(n,o,s.bytes))}else if(t[lz]===!0){let{version:n,multihash:o,code:s}=t,i=ek(o);return r.create(n,s,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!==Tf)throw new Error(`Version 0 CID must use dag-pb (code: ${Tf}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=lk(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Tf,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=jo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new pl(t.multihashCode,t.digestSize,s,o);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]=Af(e.subarray(t));return t+=f,d},o=n(),s=Tf;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=sz(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return x7(s).set(n,e),s}};function sz(r,e){switch(r[0]){case"Q":{let t=e??oo;return[oo.prefix,t.decode(`${oo.prefix}${r}`)]}case oo.prefix:{let t=e??oo;return[oo.prefix,t.decode(r)]}case dl.prefix:{let t=e??dl;return[dl.prefix,t.decode(r)]}case vf.prefix:{let t=e??vf;return[vf.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 iz(r,e,t){let{prefix:n}=t;if(n!==oo.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function az(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Tf=112,cz=18;function lk(r,e,t){let n=hl(r),o=n+hl(e),s=new Uint8Array(o+t.byteLength);return fl(r,s,0),fl(e,s,n),s.set(t,o),s}var lz=Symbol.for("@ipld/js-cid/CID");var E7={...p7,...a7,...h7,...s7,...i7,...l7,...u7,...d7,...f7,...c7},fbe={...b7,...g7};function uk(r=0){return new Uint8Array(r)}function fk(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var dk=fk("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),v7=fk("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=uk(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),uz={utf8:dk,"utf-8":dk,hex:E7.base16,latin1:v7,ascii:v7,binary:v7,...E7},hk=uz;function ha(r,e="utf8"){let t=hk[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var b2=class extends globalThis.Request{constructor(e,t={}){let n=t.method??"GET",o=so(t),s=t.body;x2(n,o)&&(t.method="UPGRADE"),super(e,t),Object.defineProperties(this,{body:{value:s,writable:!1},method:{value:n,writable:!1},headers:{value:o,writable:!1}})}};var pk={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var io=class extends globalThis.Response{constructor(e,t={}){let n=so(t),o=t.status??200;(o<200||o>599)&&(t.status=200),super(e,t),Object.defineProperties(this,{status:{value:o,writable:!1},statusText:{value:pk[o],writable:!1},headers:{value:n,writable:!1}})}};var dz=["dns","dns4","dns6","dnsaddr"];function kf(r,e){if(r instanceof URL)return r;let t=v2(r,e),{httpPath:n}=S2(r);return new URL(`http://${t}${n}`)}function _f(r){return r instanceof Uint8Array?r:r instanceof DataView?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r,0,r.byteLength)}function yk(r,e){let t={method:r.method,headers:r.headers};if((t.method!=="GET"||r.upgrade)&&t.method!=="HEAD"){let n=e;r.upgrade||(n=hz(e,r.headers.get("content-length"))),t.body=e7(n),t.duplex="half"}return new b2(S7(r).toString(),t)}async function wk(r,e){if(e.send(ha([`HTTP/1.1 ${r.status} ${r.statusText}`,...E2(r.headers),"",""].join(`\r
|
|
49
|
+
`)}`:`${t} :`}};YA=Ds;J.Constructed=YA;Ds.NAME="CONSTRUCTED";var Jm=class extends Vt{fromBER(e,t,n){return t}toBER(e){return Xn}};Jm.override="EndOfContentValueBlock";var XA,Zm=class extends Rt{constructor(e={}){super(e,Jm),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};XA=Zm;J.EndOfContent=XA;Zm.NAME=Bd;var QA,oa=class extends Rt{constructor(e={}){super(e,Vt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};QA=oa;J.Null=QA;oa.NAME="NULL";var e0=class extends Vo(Vt){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ve.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);return Ko(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,l8.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};e0.NAME="BooleanValueBlock";var JA,t0=class extends Rt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,e0),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};JA=t0;J.Boolean=JA;t0.NAME="BOOLEAN";var r0=class extends Vo(jn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,o){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=jn.prototype.fromBER.call(this,e,t,n,o),s===-1)return s;for(let i=0;i<this.value.length;i++){let a=this.value[i].constructor.NAME;if(a===Bd){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==qA)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?jn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};r0.NAME="OctetStringValueBlock";var h8,Uo=class extends Rt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},r0),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,o){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let a=o??Vd(),c=f8(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ds.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=ve.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof h8&&e.push(t.valueBlock.valueHexView);return ve.BufferSourceConverter.concat(e)}};h8=Uo;J.OctetString=h8;Uo.NAME=qA;var n0=class extends Vo(jn){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,o){if(!n)return t;let s=-1;if(this.isConstructed){if(s=jn.prototype.fromBER.call(this,e,t,n,o),s===-1)return s;for(let c of this.value){let l=c.constructor.NAME;if(l===Bd){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(l!==zA)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return s}let i=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,i,t,n))return-1;let a=i.subarray(t,t+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let l=o??Vd(),u=f8(c,0,c.byteLength,l);u.offset!==-1&&u.offset===n-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+n}toBER(e,t){if(this.isConstructed)return jn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let o=new Uint8Array(1);return o[0]=0,o.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};n0.NAME="BitStringValueBlock";var ZA,o0=class extends Rt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},n0),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,o){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ds.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let i of t)e.push(i.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};ZA=o0;J.BitString=ZA;o0.NAME=zA;var eI;function _$(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,d=0;for(let f=u;f>=0;f--,d++)!0===d<a.length?l=s[i-d]+a[c-d]+t[0]:l=s[i-d]+t[0],t[0]=l/10,!0===d>=s.length?s=zm(new Uint8Array([l%10]),s):s[i-d]=l%10;return t[0]>0&&(s=zm(t,s)),s}function HA(r){if(r>=Rd.length)for(let e=Rd.length;e<=r;e++){let t=new Uint8Array([0]),n=Rd[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=zm(t,n)),Rd.push(n)}return Rd[r]}function P$(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let d=c;d>=0;d--,u++)l=s[i-u]-a[c-u]-t,!0===l<0?(t=1,s[i-u]=l+10):(t=0,s[i-u]=l);if(t>0)for(let d=i-c+1;d>=0;d--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var Md=class extends Vo(Vt){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=l8.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array($A(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++)(o&1)===1&&(n===e?(t=P$(HA(n),t),i="-"):t=_$(t,HA(n))),n++,o>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=VA.charAt(t[c]));return a===!1&&(i+=VA.charAt(0)),i}};eI=Md;Md.NAME="IntegerValueBlock";Object.defineProperty(eI.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Nd,Fo=class extends Rt{constructor(e={}){super(e,Md),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Wm(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Wm();let t=BigInt(e),n=new Od,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(ve.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${ve.Convert.ToHex(a)}`)+t,u=ve.BufferSourceConverter.toUint8Array(ve.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new Nd({valueHex:n.final()})}convertToDER(){let e=new Nd({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Nd({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Nd=Fo;J.Integer=Nd;Fo.NAME="INTEGER";var tI,s0=class extends Fo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};tI=s0;J.Enumerated=tI;s0.NAME="ENUMERATED";var Ud=class extends Vo(Vt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=na(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Wm();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Ls(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xn;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=ve.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Ud.NAME="sidBlock";var i0=class extends Vt{constructor({value:e=Bc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Ud;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Xn;t.push(o)}return u8(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Ud;if(o>Number.MAX_SAFE_INTEGER){Wm();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};i0.NAME="ObjectIdentifierValueBlock";var rI,Yn=class extends Rt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,i0),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};rI=Yn;J.ObjectIdentifier=rI;Yn.NAME="OBJECT IDENTIFIER";var Fd=class extends Vo(Mo){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ve.BufferSourceConverter.toUint8Array(e);if(!Ko(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=na(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Ls(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xn;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ve.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Fd.NAME="relativeSidBlock";var a0=class extends Vt{constructor({value:e=Bc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Fd;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,Xn;n.push(s)}return u8(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Fd;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};a0.NAME="RelativeObjectIdentifierValueBlock";var nI,c0=class extends Rt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,a0),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};nI=c0;J.RelativeObjectIdentifier=nI;c0.NAME="RelativeObjectIdentifier";var oI,Sr=class extends Ds{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};oI=Sr;J.Sequence=oI;Sr.NAME="SEQUENCE";var sI,l0=class extends Ds{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};sI=l0;J.Set=sI;l0.NAME="SET";var u0=class extends Vo(Vt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Bc}toJSON(){return{...super.toJSON(),value:this.value}}};u0.NAME="StringValueBlock";var d0=class extends u0{};d0.NAME="SimpleStringValueBlock";var hr=class extends Ym{constructor({...e}={}){super(e,d0)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ve.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};hr.NAME="SIMPLE STRING";var f0=class extends hr{fromBuffer(e){this.valueBlock.valueHexView=ve.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ve.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ve.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ve.Convert.FromUtf8String(e)),this.valueBlock.value=e}};f0.NAME="Utf8StringValueBlock";var iI,$o=class extends f0{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};iI=$o;J.Utf8String=iI;$o.NAME="UTF8String";var h0=class extends hr{fromBuffer(e){this.valueBlock.value=ve.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ve.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ve.Convert.FromUtf16String(e))}};h0.NAME="BmpStringValueBlock";var aI,p0=class extends h0{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};aI=p0;J.BmpString=aI;p0.NAME="BMPString";var m0=class extends hr{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Ls(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};m0.NAME="UniversalStringValueBlock";var cI,g0=class extends m0{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};cI=g0;J.UniversalString=cI;g0.NAME="UniversalString";var lI,y0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};lI=y0;J.NumericString=lI;y0.NAME="NumericString";var uI,w0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};uI=w0;J.PrintableString=uI;w0.NAME="PrintableString";var dI,b0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};dI=b0;J.TeletexString=dI;b0.NAME="TeletexString";var fI,x0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};fI=x0;J.VideotexString=fI;x0.NAME="VideotexString";var hI,E0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};hI=E0;J.IA5String=hI;E0.NAME="IA5String";var pI,v0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};pI=v0;J.GraphicString=pI;v0.NAME="GraphicString";var mI,$d=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};mI=$d;J.VisibleString=mI;$d.NAME="VisibleString";var gI,S0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};gI=S0;J.GeneralString=gI;S0.NAME="GeneralString";var yI,A0=class extends hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};yI=A0;J.CharacterString=yI;A0.NAME="CharacterString";var wI,Kd=class extends $d{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ve.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=vr(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=vr(this.month,2),t[2]=vr(this.day,2),t[3]=vr(this.hour,2),t[4]=vr(this.minute,2),t[5]=vr(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};wI=Kd;J.UTCTime=wI;Kd.NAME="UTCTime";var bI,I0=class extends Kd{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,f=n.indexOf("+"),h="";if(f===-1&&(f=n.indexOf("-"),d=-1),f!==-1){if(h=n.substring(f+1),n=n.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=d*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let d=new Number(`0${n.substring(l)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");s=d.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*s;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*s;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=1e3*s;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let d=1;d<u.length;d++)switch(d){case 1:this.year=parseInt(u[d],10);break;case 2:this.month=parseInt(u[d],10);break;case 3:this.day=parseInt(u[d],10);break;case 4:this.hour=parseInt(u[d],10)+a;break;case 5:this.minute=parseInt(u[d],10)+c;break;case 6:this.second=parseInt(u[d],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(vr(this.year,4)),t.push(vr(this.month,2)),t.push(vr(this.day,2)),t.push(vr(this.hour,2)),t.push(vr(this.minute,2)),t.push(vr(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(vr(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};bI=I0;J.GeneralizedTime=bI;I0.NAME="GeneralizedTime";var xI,T0=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};xI=T0;J.DATE=xI;T0.NAME="DATE";var EI,C0=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};EI=C0;J.TimeOfDay=EI;C0.NAME="TimeOfDay";var vI,k0=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};vI=k0;J.DateTime=vI;k0.NAME="DateTime";var SI,_0=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};SI=_0;J.Duration=SI;_0.NAME="Duration";var AI,P0=class extends $o{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};AI=P0;J.TIME=AI;P0.NAME="TIME";async function D0(r,e){let n=await Nc.create().encrypt(r,e);return $e.encode(n)}async function p8(r,e,t){if(r.type==="RSA")return N$(r,e,t);if(r.type==="Ed25519")return L$(r,e,t);if(r.type==="secp256k1")return D$(r,e,t);if(r.type==="ECDSA")return R$(r,e,t);throw new cn}async function L$(r,e,t="libp2p-key"){if(t==="libp2p-key")return D0(Gi(r),e);throw new A(`export format '${t}' is not supported`)}async function D$(r,e,t="libp2p-key"){if(t==="libp2p-key")return D0(Gi(r),e);throw new A("Export format is not supported")}async function R$(r,e,t="libp2p-key"){if(t==="libp2p-key")return D0(Gi(r),e);throw new A(`export format '${t}' is not supported`)}async function N$(r,e,t="pkcs-8"){if(t==="pkcs-8")return O$(r,e);if(t==="libp2p-key")return D0(Gi(r),e);throw new A("Export format is not supported")}async function O$(r,e){let t=yt.get(),o=new Sr({value:[new Fo({value:0}),new Sr({value:[new Yn({value:"1.2.840.113549.1.1.1"}),new oa]}),new Uo({valueHex:r.raw})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=t.getRandomValues(new Uint8Array(16)),a=await Km(Hn,e,i,{c:1e4,dkLen:32}),c=t.getRandomValues(new Uint8Array(16)),l=await t.subtle.importKey("raw",ee(a),"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:ee(c)},l,ee(s)),d=new Sr({value:[new Uo({valueHex:i}),new Fo({value:1e4}),new Fo({value:32}),new Sr({value:[new Yn({value:"1.2.840.113549.2.11"}),new oa]})]}),f=new Sr({value:[new Yn({value:"1.2.840.113549.1.5.13"}),new Sr({value:[new Sr({value:[new Yn({value:"1.2.840.113549.1.5.12"}),d]}),new Sr({value:[new Yn({value:"2.16.840.1.101.3.4.1.42"}),new Uo({valueHex:c})]})]})]}),p=new Sr({value:[f,new Uo({valueHex:u})]}).toBER(),y=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...M(y,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
50
|
+
`)}async function m8(r,e){try{let t=await B$(r,e);return Xv(t)}catch{}if(!r.includes("BEGIN"))throw new A("Encrypted key was not a libp2p-key or a PEM file");return M$(r,e)}async function B$(r,e){let t=$e.decode(r);return Nc.create().decrypt(t,e)}async function M$(r,e){let t=yt.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=L0(s),{iv:a,salt:c,iterations:l,keySize:u,cipherText:d}=U$(i),f=await Km(Hn,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",ee(f),"AES-CBC",!1,["decrypt"]),p=Hd(await t.subtle.decrypt({name:"AES-CBC",iv:ee(a)},h,ee(d))),{result:y}=L0(p);n=kI(y)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=L0(s);n=kI(i)}else throw new A("Could not parse private key from PEM data");let o=Qv(n);if(o.type!=="RSA")throw new A("Could not parse RSA private key from PEM data");return o}function U$(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new A("Only pkcs5PBES2 encrypted private keys are supported");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new A("Only pkcs5PBKDF2 key derivation functions are supported");let s=n.valueBlock.value[1],i=Hd(s.valueBlock.value[0].getValue()),a=1e4,c=32;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new A("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");let l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new A("Only AES-CBC encryption schemes are supported")}}}}let d=Hd(l.valueBlock.value[1].getValue());return{cipherText:Hd(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:d}}function kI(r){return Hd(r.valueBlock.value[2].getValue())}function Hd(r){return new Uint8Array(r,0,r.byteLength)}var F$="/pkcs8/",g8="/info/",qd=new WeakMap,sa={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function Mc(r){return r==null||typeof r!="string"?!1:r===(0,_I.default)(r.trim())&&r.length>0}async function Ht(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function ia(r){return new Me(F$+r)}function Uc(r){return new Me(g8+r)}async function $$(r){let e=Gi(r),t=await He.digest(e);return ge.encode(t.bytes).substring(1)}var R0=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...a8,...t.dek}},this.self=t.selfKey??"self",this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<sa.minKeyLength)throw new Error(`dek.keyLength must be least ${sa.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<sa.minSaltLength)throw new Error(`dek.saltLength must be least ${sa.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<sa.minIterationCount)throw new Error(`dek.iterationCount must be least ${sa.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?Dd(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";qd.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[xe]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(sa.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=M(crypto.getRandomValues(new Uint8Array(t)),"base64")),e}static get options(){return{dek:{...a8}}}async findKeyByName(e){if(!Mc(e))throw await Ht(),new A(`Invalid key name '${e}'`);let t=Uc(e);try{let n=await this.components.datastore.get(t);return JSON.parse(M(n))}catch(n){throw await Ht(),this.log.error("could not read key from datastore - %e",n),new Te(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:g8};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(M(n.value));if(o.id===e)return o}throw new A(`Key with id '${e}' does not exist.`)}catch(t){throw await Ht(),t}}async importKey(e,t){if(!Mc(e))throw await Ht(),new A(`Invalid key name '${e}'`);if(t==null)throw await Ht(),new A("Key is required");let n=ia(e);if(await this.components.datastore.has(n))throw await Ht(),new A(`Key '${e}' already exists`);let s,i;try{s=await $$(t);let l=qd.get(this);if(l==null)throw new A("dek missing");let u=l.dek;i=await p8(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await Ht(),l}let a={name:e,id:s},c=this.components.datastore.batch();return c.put(n,O(i)),c.put(Uc(e),O(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!Mc(e))throw await Ht(),new A(`Invalid key name '${e}'`);let t=ia(e);try{let n=await this.components.datastore.get(t),o=M(n),s=qd.get(this);if(s==null)throw new A("dek missing");let i=s.dek;return await m8(o,i)}catch(n){throw await Ht(),n}}async removeKey(e){if(!Mc(e)||e===this.self)throw await Ht(),new A(`Invalid key name '${e}'`);let t=ia(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(Uc(e)),await o.commit(),n}async listKeys(){let e={prefix:g8},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(M(n.value)));return t}async renameKey(e,t){if(!Mc(e)||e===this.self)throw await Ht(),new A(`Invalid old key name '${e}'`);if(!Mc(t)||t===this.self)throw await Ht(),new A(`Invalid new key name '${t}'`);let n=ia(e),o=ia(t),s=Uc(e),i=Uc(t);if(await this.components.datastore.has(o))throw await Ht(),new A(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(M(l));u.name=t;let d=this.components.datastore.batch();return d.put(o,c),d.put(i,O(JSON.stringify(u))),d.delete(n),d.delete(s),await d.commit(),u}catch(c){throw await Ht(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await Ht(),new A(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await Ht(),new A(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await Ht(),new A(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=qd.get(this);if(n==null)throw new A("dek missing");let o=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?Dd(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";qd.set(this,{dek:s});let i=await this.listKeys();for(let a of i){let c=await this.components.datastore.get(ia(a.name)),l=M(c),u=await m8(l,o),d=s.toString(),f=await p8(u,d,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(ia(a.name),O(f)),h.put(Uc(a.name),O(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function PI(r={}){return e=>new R0(e,r)}async function y8(r,e={}){let t=e.selfKey??"self",n=PI(e)({datastore:r,logger:tc()}),o;return await r.has(new Me(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await rp(e.keyType??"Ed25519"),await n.importKey(t,o)),o}function St(r=0){return new Uint8Array(r)}function er(r=0){return new Uint8Array(r)}var Fc=!!globalThis.process?.env?.DUMP_SESSION_KEYS,w8=16;function K$(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function N0(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function $c(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function At(r,e,t=""){let n=K$(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function b8(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function LI(r,e,t=!1){At(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!Kc(r))throw new Error("invalid output, must be aligned")}function Qn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function _n(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function V$(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var aa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,H$=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var q$=r=>{for(let e=0;e<r.length;e++)r[e]=H$(r[e]);return r},Ho=aa?r=>r:q$;function DI(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function RI(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function NI(r,e,t){let n=e,o=t||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(r),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var OI=(r,e)=>{function t(n,...o){if(At(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];At(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&At(o[1],void 0,"AAD");let i=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");At(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,At(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(At(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function zd(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(At(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!Kc(e))throw new Error("invalid output, must be aligned");return e}function BI(r,e,t){$c(r),$c(e),N0(t);let n=new Uint8Array(16),o=V$(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function Kc(r){return r.byteOffset%4===0}function Vc(r){return Uint8Array.from(At(r))}var UI=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),z$=Ho(Qn(UI("expand 16-byte k"))),W$=Ho(Qn(UI("expand 32-byte k")));function Ae(r,e){return r<<e|r>>>32-e}var Wd=64,G$=16,x8=2**32-1,MI=Uint32Array.of();function j$(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(Wd),u=Qn(l),d=aa&&Kc(o)&&Kc(s),f=d?Qn(o):MI,h=d?Qn(s):MI;if(!aa){for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),Ho(u),i>=x8)throw new Error("arx: counter overflow");let y=Math.min(Wd,c-p);for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}return}for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),i>=x8)throw new Error("arx: counter overflow");let y=Math.min(Wd,c-p);if(d&&y===Wd){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,w;m<G$;m++)w=g+m,h[w]=f[w]^u[m];p+=Wd;continue}for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}}function FI(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=DI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return $c(o),$c(i),N0(s),N0(t),(a,c,l,u,d=0)=>{At(a,void 0,"key"),At(c,void 0,"nonce"),At(l,void 0,"data");let f=l.length;if(u=zd(f,u,!1),$c(d),d<0||d>=x8)throw new Error("arx: counter overflow");let h=[],p=a.length,y,g;if(p===32)h.push(y=Vc(a)),g=W$;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=z$,h.push(y);else throw At(a,32,"arx key"),new Error("invalid key size");(!aa||!Kc(c))&&h.push(c=Vc(c));let m=Qn(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let E=c.subarray(0,16);if(aa)n(g,m,Qn(E),m);else{let S=Ho(Uint32Array.from(g));n(S,m,Qn(E),m),_n(S),Ho(m)}c=c.subarray(16)}else aa||Ho(m);let w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let E=new Uint8Array(12);E.set(c,s?0:12-c.length),c=E,h.push(c)}let x=Ho(Qn(c));try{return j$(r,g,m,x,l,u,d,i),u}finally{_n(...h)}}}function qt(r,e){return r[e++]&255|(r[e++]&255)<<8}var E8=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Vc(At(e,32,"key"));let t=qt(e,0),n=qt(e,2),o=qt(e,4),s=qt(e,6),i=qt(e,8),a=qt(e,10),c=qt(e,12),l=qt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=qt(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],f=i[5],h=i[6],p=i[7],y=i[8],g=i[9],m=qt(e,t+0),w=qt(e,t+2),x=qt(e,t+4),E=qt(e,t+6),S=qt(e,t+8),T=qt(e,t+10),I=qt(e,t+12),C=qt(e,t+14),U=s[0]+(m&8191),j=s[1]+((m>>>13|w<<3)&8191),z=s[2]+((w>>>10|x<<6)&8191),v=s[3]+((x>>>7|E<<9)&8191),D=s[4]+((E>>>4|S<<12)&8191),L=s[5]+(S>>>1&8191),_=s[6]+((S>>>14|T<<2)&8191),k=s[7]+((T>>>11|I<<5)&8191),N=s[8]+((I>>>8|C<<8)&8191),F=s[9]+(C>>>5|o),P=0,$=P+U*a+j*(5*g)+z*(5*y)+v*(5*p)+D*(5*h);P=$>>>13,$&=8191,$+=L*(5*f)+_*(5*d)+k*(5*u)+N*(5*l)+F*(5*c),P+=$>>>13,$&=8191;let H=P+U*c+j*a+z*(5*g)+v*(5*y)+D*(5*p);P=H>>>13,H&=8191,H+=L*(5*h)+_*(5*f)+k*(5*d)+N*(5*u)+F*(5*l),P+=H>>>13,H&=8191;let Z=P+U*l+j*c+z*a+v*(5*g)+D*(5*y);P=Z>>>13,Z&=8191,Z+=L*(5*p)+_*(5*h)+k*(5*f)+N*(5*d)+F*(5*u),P+=Z>>>13,Z&=8191;let fe=P+U*u+j*l+z*c+v*a+D*(5*g);P=fe>>>13,fe&=8191,fe+=L*(5*y)+_*(5*p)+k*(5*h)+N*(5*f)+F*(5*d),P+=fe>>>13,fe&=8191;let ue=P+U*d+j*u+z*l+v*c+D*a;P=ue>>>13,ue&=8191,ue+=L*(5*g)+_*(5*y)+k*(5*p)+N*(5*h)+F*(5*f),P+=ue>>>13,ue&=8191;let Ne=P+U*f+j*d+z*u+v*l+D*c;P=Ne>>>13,Ne&=8191,Ne+=L*a+_*(5*g)+k*(5*y)+N*(5*p)+F*(5*h),P+=Ne>>>13,Ne&=8191;let Oe=P+U*h+j*f+z*d+v*u+D*l;P=Oe>>>13,Oe&=8191,Oe+=L*c+_*a+k*(5*g)+N*(5*y)+F*(5*p),P+=Oe>>>13,Oe&=8191;let Be=P+U*p+j*h+z*f+v*d+D*u;P=Be>>>13,Be&=8191,Be+=L*l+_*c+k*a+N*(5*g)+F*(5*y),P+=Be>>>13,Be&=8191;let Ie=P+U*y+j*p+z*h+v*f+D*d;P=Ie>>>13,Ie&=8191,Ie+=L*u+_*l+k*c+N*a+F*(5*g),P+=Ie>>>13,Ie&=8191;let Je=P+U*g+j*y+z*p+v*h+D*f;P=Je>>>13,Je&=8191,Je+=L*d+_*u+k*l+N*c+F*a,P+=Je>>>13,Je&=8191,P=(P<<2)+P|0,P=P+$|0,$=P&8191,P=P>>>13,H+=P,s[0]=$,s[1]=H,s[2]=Z,s[3]=fe,s[4]=ue,s[5]=Ne,s[6]=Oe,s[7]=Be,s[8]=Ie,s[9]=Je}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;_n(n)}update(e){b8(this),At(e),e=Vc(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,_n(this.h,this.r,this.buffer,this.pad)}digestInto(e){b8(this),LI(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},$I=NI(32,r=>new E8(r));function Y$(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],f=e[2],h=e[3],p=e[4],y=e[5],g=e[6],m=e[7],w=o,x=t[0],E=t[1],S=t[2],T=i,I=a,C=c,U=l,j=u,z=d,v=f,D=h,L=p,_=y,k=g,N=m,F=w,P=x,$=E,H=S;for(let fe=0;fe<s;fe+=2)T=T+j|0,F=Ae(F^T,16),L=L+F|0,j=Ae(j^L,12),T=T+j|0,F=Ae(F^T,8),L=L+F|0,j=Ae(j^L,7),I=I+z|0,P=Ae(P^I,16),_=_+P|0,z=Ae(z^_,12),I=I+z|0,P=Ae(P^I,8),_=_+P|0,z=Ae(z^_,7),C=C+v|0,$=Ae($^C,16),k=k+$|0,v=Ae(v^k,12),C=C+v|0,$=Ae($^C,8),k=k+$|0,v=Ae(v^k,7),U=U+D|0,H=Ae(H^U,16),N=N+H|0,D=Ae(D^N,12),U=U+D|0,H=Ae(H^U,8),N=N+H|0,D=Ae(D^N,7),T=T+z|0,H=Ae(H^T,16),k=k+H|0,z=Ae(z^k,12),T=T+z|0,H=Ae(H^T,8),k=k+H|0,z=Ae(z^k,7),I=I+v|0,F=Ae(F^I,16),N=N+F|0,v=Ae(v^N,12),I=I+v|0,F=Ae(F^I,8),N=N+F|0,v=Ae(v^N,7),C=C+D|0,P=Ae(P^C,16),L=L+P|0,D=Ae(D^L,12),C=C+D|0,P=Ae(P^C,8),L=L+P|0,D=Ae(D^L,7),U=U+j|0,$=Ae($^U,16),_=_+$|0,j=Ae(j^_,12),U=U+j|0,$=Ae($^U,8),_=_+$|0,j=Ae(j^_,7);let Z=0;n[Z++]=i+T|0,n[Z++]=a+I|0,n[Z++]=c+C|0,n[Z++]=l+U|0,n[Z++]=u+j|0,n[Z++]=d+z|0,n[Z++]=f+v|0,n[Z++]=h+D|0,n[Z++]=p+L|0,n[Z++]=y+_|0,n[Z++]=g+k|0,n[Z++]=m+N|0,n[Z++]=w+F|0,n[Z++]=x+P|0,n[Z++]=E+$|0,n[Z++]=S+H|0}var X$=FI(Y$,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Q$=new Uint8Array(16),KI=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(Q$.subarray(t))},J$=new Uint8Array(32);function VI(r,e,t,n,o){o!==void 0&&At(o,void 0,"AAD");let s=r(e,t,J$),i=BI(n.length,o?o.length:0,!0),a=$I.create(s);o&&KI(a,o),KI(a,n),a.update(i);let c=a.digest();return _n(s,i),c}var Z$=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=zd(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=VI(r,e,t,c,n);return i.set(l,a),_n(l),i},decrypt(s,i){i=zd(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=VI(r,e,t,a,n);if(!RI(c,l))throw _n(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),_n(l),i}}),v8=OI({blockSize:64,nonceLength:12,tagLength:16},Z$(X$));function qI(r,e,t){return Ao(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Wi(r,t,e)}var S8=Uint8Array.of(0),HI=Uint8Array.of();function zI(r,e,t,n=32){Ao(r),xr(n,"length"),Ut(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=HI:Ut(t,void 0,"info");let i=new Uint8Array(s*o),a=Wi.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)S8[0]=u+1,c.update(u===0?HI:l).update(t).update(S8).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Qt(l,S8),i.slice(0,n)}var A8={hashSHA256(r){return Zr(r.subarray())},getHKDF(r,e){let t=qI(Zr,e,r),o=zI(Zr,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=Qu.utils.randomSecretKey();return{publicKey:Qu.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Qu.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Qu.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return v8(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return v8(n,e,t).decrypt(r.subarray(),o)}};var WI=A8;function GI(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var Hc=r=>{let e=er(2);return e[0]=r>>8,e[1]=r,e};Hc.bytes=2;var qc=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};qc.bytes=2;function jI(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var _8={};V(_8,{base10:()=>iK});var X3e=new Uint8Array(0);function YI(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 qo(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function XI(r){return new TextEncoder().encode(r)}function QI(r){return new TextDecoder().decode(r)}function eK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,y++;for(var x=(w-m)*u+1>>>0,E=new Uint8Array(x);m!==w;){for(var S=p[m],T=0,I=x-1;(S!==0||T<g)&&I!==-1;I--,T++)S+=256*E[I]>>>0,E[I]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");g=T,m++}for(var C=x-g;C!==x&&E[C]===0;)C++;for(var U=c.repeat(y);C<x;++C)U+=r.charAt(E[C]);return U}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var w=(p.length-y)*l+1>>>0,x=new Uint8Array(w);p[y];){var E=t[p.charCodeAt(y)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<m)&&T!==-1;T--,S++)E+=a*x[T]>>>0,x[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");m=S,y++}if(p[y]!==" "){for(var I=w-m;I!==w&&x[I]===0;)I++;for(var C=new Uint8Array(g+(w-I)),U=g;I!==w;)C[U++]=x[I++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var tK=eK,rK=tK,ZI=rK;var I8=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")}},T8=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return eT(this,e)}},C8=class{decoders;constructor(e){this.decoders=e}or(e){return eT(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 eT(r,e){return new C8({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var k8=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new I8(e,t,n),this.decoder=new T8(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zc({name:r,prefix:e,encode:t,decode:n}){return new k8(r,e,t,n)}function Rs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=ZI(t,r);return zc({prefix:e,name:r,encode:n,decode:s=>qo(o(s))})}function nK(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function oK(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function sK(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ct({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=sK(n);return zc({prefix:e,name:r,encode(s){return oK(s,n,t)},decode(s){return nK(s,o,t,r)}})}var iK=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var P8={};V(P8,{base16:()=>aK,base16upper:()=>cK});var aK=ct({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cK=ct({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var L8={};V(L8,{base2:()=>lK});var lK=ct({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var D8={};V(D8,{base256emoji:()=>pK});var tT=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}"),uK=tT.reduce((r,e,t)=>(r[t]=e,r),[]),dK=tT.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function fK(r){return r.reduce((e,t)=>(e+=uK[t],e),"")}function hK(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=dK[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var pK=zc({prefix:"\u{1F680}",name:"base256emoji",encode:fK,decode:hK});var R8={};V(R8,{base32:()=>Wc,base32hex:()=>wK,base32hexpad:()=>xK,base32hexpadupper:()=>EK,base32hexupper:()=>bK,base32pad:()=>gK,base32padupper:()=>yK,base32upper:()=>mK,base32z:()=>vK});var Wc=ct({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mK=ct({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gK=ct({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yK=ct({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wK=ct({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bK=ct({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xK=ct({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),EK=ct({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vK=ct({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var N8={};V(N8,{base36:()=>Gd,base36upper:()=>SK});var Gd=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),SK=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var O8={};V(O8,{base58btc:()=>Jn,base58flickr:()=>AK});var Jn=Rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),AK=Rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var B8={};V(B8,{base64:()=>IK,base64pad:()=>TK,base64url:()=>CK,base64urlpad:()=>kK});var IK=ct({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),TK=ct({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CK=ct({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kK=ct({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var M8={};V(M8,{base8:()=>_K});var _K=ct({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var U8={};V(U8,{identity:()=>PK});var PK=zc({prefix:"\0",name:"identity",encode:r=>QI(r),decode:r=>XI(r)});var f4e=new TextEncoder,h4e=new TextDecoder;var $8={};V($8,{identity:()=>ZK});var RK=oT,rT=128,NK=127,OK=~NK,BK=Math.pow(2,31);function oT(r,e,t){e=e||[],t=t||0;for(var n=t;r>=BK;)e[t++]=r&255|rT,r/=128;for(;r&OK;)e[t++]=r&255|rT,r>>>=7;return e[t]=r|0,oT.bytes=t-n+1,e}var MK=F8,UK=128,nT=127;function F8(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw F8.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&nT)<<o:(i&nT)*Math.pow(2,o),o+=7}while(i>=UK);return F8.bytes=s-n,t}var FK=Math.pow(2,7),$K=Math.pow(2,14),KK=Math.pow(2,21),VK=Math.pow(2,28),HK=Math.pow(2,35),qK=Math.pow(2,42),zK=Math.pow(2,49),WK=Math.pow(2,56),GK=Math.pow(2,63),jK=function(r){return r<FK?1:r<$K?2:r<KK?3:r<VK?4:r<HK?5:r<qK?6:r<zK?7:r<WK?8:r<GK?9:10},YK={encode:RK,decode:MK,encodingLength:jK},XK=YK,jd=XK;function Yd(r,e=0){return[jd.decode(r,e),jd.decode.bytes]}function Gc(r,e,t=0){return jd.encode(r,e,t),e}function jc(r){return jd.encodingLength(r)}function Xc(r,e){let t=e.byteLength,n=jc(r),o=n+jc(t),s=new Uint8Array(o+t);return Gc(r,s,0),Gc(t,s,n),s.set(e,o),new Yc(r,t,e,s)}function sT(r){let e=qo(r),[t,n]=Yd(e),[o,s]=Yd(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Yc(t,o,i,e)}function iT(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&YI(r.bytes,t.bytes)}}var Yc=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var aT=0,QK="identity",cT=qo;function JK(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 Xc(aT,cT(r))}var ZK={code:aT,name:QK,encode:cT,digest:JK};var H8={};V(H8,{sha256:()=>tV,sha512:()=>rV});var eV=20;function V8({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new K8(r,e,t,n,o)}var K8=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??eV,this.maxDigestLength=s}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?lT(n,this.code,t?.truncate):n.then(o=>lT(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function lT(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 Xc(e,r)}function dT(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var tV=V8({name:"sha2-256",code:18,encode:dT("SHA-256")}),rV=V8({name:"sha2-512",code:19,encode:dT("SHA-512")});function fT(r,e){let{bytes:t,version:n}=r;return n===0?oV(t,q8(r),e??Jn.encoder):sV(t,q8(r),e??Wc.encoder)}var hT=new WeakMap;function q8(r){let e=hT.get(r);if(e==null){let t=new Map;return hT.set(r,t),t}return e}var B0=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Qd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==iV)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=Xc(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&&iT(e.multihash,n.multihash)}toString(e){return fT(this,e)}toJSON(){return{"/":fT(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??pT(n,o,s.bytes))}else if(t[aV]===!0){let{version:n,multihash:o,code:s}=t,i=sT(o);return r.create(n,s,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!==Qd)throw new Error(`Version 0 CID must use dag-pb (code: ${Qd}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=pT(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Qd,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=qo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Yc(t.multihashCode,t.digestSize,s,o);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]=Yd(e.subarray(t));return t+=f,d},o=n(),s=Qd;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=nV(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return q8(s).set(n,e),s}};function nV(r,e){switch(r[0]){case"Q":{let t=e??Jn;return[Jn.prefix,t.decode(`${Jn.prefix}${r}`)]}case Jn.prefix:{let t=e??Jn;return[Jn.prefix,t.decode(r)]}case Wc.prefix:{let t=e??Wc;return[Wc.prefix,t.decode(r)]}case Gd.prefix:{let t=e??Gd;return[Gd.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 oV(r,e,t){let{prefix:n}=t;if(n!==Jn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function sV(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Qd=112,iV=18;function pT(r,e,t){let n=jc(r),o=n+jc(e),s=new Uint8Array(o+t.byteLength);return Gc(r,s,0),Gc(e,s,n),s.set(t,o),s}var aV=Symbol.for("@ipld/js-cid/CID");var z8={...U8,...L8,...M8,..._8,...P8,...R8,...N8,...O8,...B8,...D8},O4e={...H8,...$8};function gT(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var mT=gT("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),W8=gT("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=er(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),cV={utf8:mT,"utf-8":mT,hex:z8.base16,latin1:W8,ascii:W8,binary:W8,...z8},M0=cV;function Zn(r,e="utf8"){let t=M0[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function G8(r,e){!e.enabled||!Fc||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${Zn(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${Zn(r.privateKey,"hex")}`)):e("Missing local static keys."))}function j8(r,e){!e.enabled||!Fc||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Zn(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Zn(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function yT(r,e){!e.enabled||!Fc||e(r?`REMOTE_STATIC_PUBLIC_KEY ${Zn(r.subarray(),"hex")}`:"Missing remote static public key.")}function Y8(r,e){!e.enabled||!Fc||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Zn(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function X8(r,e,t){!t.enabled||!Fc||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&Zn(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&Zn(e.k,"hex")}`))}function Qc(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=er(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Q8(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 bT=Symbol.for("@achingbrain/uint8arraylist");function wT(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function U0(r){return!!r?.[bT]}var eo=class r{bufs;length;[bT]=!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(U0(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(U0(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=wT(this.bufs,e);return t.buf[t.index]}set(e,t){let n=wT(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(U0(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Qc(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Qc(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(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(!U0(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;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=er(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=St(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=St(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=St(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=er(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=St(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=St(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=St(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=St(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=St(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q8(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function ca(r,e="utf8"){let t=M0[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Jc=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var uV=0,dV=4294967295,fV="Cipherstate has reached maximum n, a new handshake must be performed",F0=class{n;bytes;view;constructor(e=uV){this.n=e,this.bytes=St(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>dV)throw new Error(fV)}};var la=St(0),Zc=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new F0(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},J8=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=ca(t,"utf-8");this.h=hV(e,n),this.ck=this.h,this.cs=new Zc(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Zc(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new eo(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,la);return[new Zc(this.crypto,e),new Zc(this.crypto,t)]}},Z8=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new J8(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Jd=class extends Z8{writeMessageA(e){return new eo(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new eo(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new eo(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Jc(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new Jc(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new Jc(`handshake stage 2 validation fail: ${t.message}`)}}};function hV(r,e){if(e.length<=32){let t=St(32);return t.set(e),t}else return r.hash(e)}var pV=Math.pow(2,7),mV=Math.pow(2,14),gV=Math.pow(2,21),xT=Math.pow(2,28),ET=Math.pow(2,35),vT=Math.pow(2,42),ST=Math.pow(2,49),pr=128,Ns=127;function Zd(r){if(r<pV)return 1;if(r<mV)return 2;if(r<gV)return 3;if(r<xT)return 4;if(r<ET)return 5;if(r<vT)return 6;if(r<ST)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function AT(r,e,t=0){switch(Zd(r)){case 8:e[t++]=r&255|pr,r/=128;case 7:e[t++]=r&255|pr,r/=128;case 6:e[t++]=r&255|pr,r/=128;case 5:e[t++]=r&255|pr,r/=128;case 4:e[t++]=r&255|pr,r>>>=7;case 3:e[t++]=r&255|pr,r>>>=7;case 2:e[t++]=r&255|pr,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function IT(r,e){let t=r[e],n=0;if(n+=t&Ns,t<pr||(t=r[e+1],n+=(t&Ns)<<7,t<pr)||(t=r[e+2],n+=(t&Ns)<<14,t<pr)||(t=r[e+3],n+=(t&Ns)<<21,t<pr)||(t=r[e+4],n+=(t&Ns)*xT,t<pr)||(t=r[e+5],n+=(t&Ns)*ET,t<pr)||(t=r[e+6],n+=(t&Ns)*vT,t<pr)||(t=r[e+7],n+=(t&Ns)*ST,t<pr))return n;throw new RangeError("Could not decode varint")}var e5=new Float32Array([-0]),Os=new Uint8Array(e5.buffer);function TT(r,e,t){e5[0]=r,e[t]=Os[0],e[t+1]=Os[1],e[t+2]=Os[2],e[t+3]=Os[3]}function CT(r,e){return Os[0]=r[e],Os[1]=r[e+1],Os[2]=r[e+2],Os[3]=r[e+3],e5[0]}var t5=new Float64Array([-0]),tr=new Uint8Array(t5.buffer);function kT(r,e,t){t5[0]=r,e[t]=tr[0],e[t+1]=tr[1],e[t+2]=tr[2],e[t+3]=tr[3],e[t+4]=tr[4],e[t+5]=tr[5],e[t+6]=tr[6],e[t+7]=tr[7]}function _T(r,e){return tr[0]=r[e],tr[1]=r[e+1],tr[2]=r[e+2],tr[3]=r[e+3],tr[4]=r[e+4],tr[5]=r[e+5],tr[6]=r[e+6],tr[7]=r[e+7],t5[0]}var yV=BigInt(Number.MAX_SAFE_INTEGER),wV=BigInt(Number.MIN_SAFE_INTEGER),Wr=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 ua;if(e<yV&&e>wV)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>PT&&(o=0n,++n>PT&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ua;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ua}},ua=new Wr(0,0);ua.toBigInt=function(){return 0n};ua.zzEncode=ua.zzDecode=function(){return this};ua.length=function(){return 1};var PT=4294967296n;function LT(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 DT(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function r5(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Pn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function $0(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var n5=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Pn(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 Pn(this,4);return $0(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Pn(this,4);return $0(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Pn(this,4);let e=CT(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Pn(this,4);let e=_T(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 Pn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return DT(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Pn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Pn(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 Wr(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 Pn(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 Pn(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 Pn(this,8);let e=$0(this.buf,this.pos+=4),t=$0(this.buf,this.pos+=4);return new Wr(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=IT(this.buf,this.pos);return this.pos+=Zd(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 o5(r){return new n5(r instanceof Uint8Array?r:r.subarray())}function K0(r,e,t){let n=o5(r);return e.decode(n,void 0,t)}function s5(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return er(i);o+i>e&&(n=er(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var da=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function i5(){}var c5=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},bV=s5();function xV(r){return globalThis.Buffer!=null?er(r):bV(r)}var tf=class{len;head;tail;states;constructor(){this.len=0,this.head=new da(i5,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new da(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new l5((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(V0,10,Wr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Wr.fromBigInt(e);return this._push(V0,t.length(),t)}uint64Number(e){return this._push(AT,Zd(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=Wr.fromBigInt(e).zzEncode();return this._push(V0,t.length(),t)}sint64Number(e){let t=Wr.fromNumber(e).zzEncode();return this._push(V0,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(a5,1,e?1:0)}fixed32(e){return this._push(ef,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Wr.fromBigInt(e);return this._push(ef,4,t.lo)._push(ef,4,t.hi)}fixed64Number(e){let t=Wr.fromNumber(e);return this._push(ef,4,t.lo)._push(ef,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(TT,4,e)}double(e){return this._push(kT,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(a5,1,0):this.uint32(t)._push(vV,t,e)}string(e){let t=LT(e);return t!==0?this.uint32(t)._push(r5,t,e):this._push(a5,1,0)}fork(){return this.states=new c5(this),this.head=this.tail=new da(i5,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 da(i5,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=xV(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function a5(r,e,t){e[t]=r&255}function EV(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var l5=class extends da{next;constructor(e,t){super(EV,e,t),this.next=void 0}};function V0(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 ef(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 vV(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(tf.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(SV,e,r),this},tf.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(AV,e,r),this});function SV(r,e,t){e.set(r,t)}function AV(r,e,t){r.length<40?r5(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(ca(r),t)}function u5(){return new tf}function H0(r,e){let t=u5();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var rf;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(rf||(rf={}));function d5(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function q0(r,e){return d5("message",rf.LENGTH_DELIMITED,r,e)}var nf=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var z0;(function(r){let e;r.codec=()=>(e==null&&(e=q0((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new nf('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new nf('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>H0(t,r.codec()),r.decode=(t,n)=>K0(t,r.codec(),n)})(z0||(z0={}));var of;(function(r){let e;r.codec=()=>(e==null&&(e=q0((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),z0.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:St(0),identitySig:St(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=z0.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>H0(t,r.codec()),r.decode=(t,n)=>K0(t,r.codec(),n)})(of||(of={}));async function h5(r,e,t){let n=await r.sign(OT(e));return of.encode({identityKey:Lt(r.publicKey),identitySig:n,extensions:t})}async function p5(r,e,t){try{let n=of.decode(r),o=Et(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=OT(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new lh(n.message)}}function OT(r){let e=ca("noise-libp2p-static-key:");return r instanceof Uint8Array?Qc([e,r],e.length+r.length):(r.prepend(e),r)}var f5=class extends cs{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new c1({lengthDecoder:qc,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new eo;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(Hc(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new eo;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-w8<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-w8);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function m5(r,e,t){return new f5(r,e,t)}async function BT(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await h5(s,a.publicKey,l),d=new Jd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});G8(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(la),e),t.trace("Stage 0 - Initiator finished sending first message."),j8(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Y8(d.re,t),yT(d.rs,t),t.trace("Initiator going to check remote's signature...");let h=await p5(f,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,y]=d.ss.split();return X8(p,y,t),{payload:h,encrypt:g=>p.encryptWithAd(la,g),decrypt:(g,m)=>y.decryptWithAd(la,g,m)}}async function MT(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await h5(s,a.publicKey,l),d=new Jd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});G8(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Y8(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),j8(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let h=await p5(f,d.rs,c),[p,y]=d.ss.split();return X8(p,y,t),{payload:h,encrypt:g=>y.encryptWithAd(la,g),decrypt:(g,m)=>p.decryptWithAd(la,g,m)}}var W0=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??WI;this.crypto=GI(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?jI(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??St(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[xe]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=fs(e,{lengthEncoder:Hc,lengthDecoder:qc,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Et(s.payload.identityKey);return{connection:m5(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Wn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new uh("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=fs(e,{lengthEncoder:Hc,lengthDecoder:qc,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Et(s.payload.identityKey);return{connection:m5(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Wn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await BT({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await MT({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function G0(r={}){return e=>new W0(e,r)}function zo(r=0){return new Uint8Array(r)}function af(r=0){return new Uint8Array(r)}function g5(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=af(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function UT(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 $T=Symbol.for("@achingbrain/uint8arraylist");function FT(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function j0(r){return!!r?.[$T]}var el=class r{bufs;length;[$T]=!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(j0(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(j0(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=FT(this.bufs,e);return t.buf[t.index]}set(e,t){let n=FT(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(j0(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return g5(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:g5(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(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(!j0(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;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=af(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=zo(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=zo(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=zo(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=af(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=zo(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=zo(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=zo(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=zo(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=zo(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!UT(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var nt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(nt||(nt={}));var ke;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(ke||(ke={}));var Yye=Object.values(ke).filter(r=>typeof r!="string"),KT=0,It;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(It||(It={}));var to=12;var Wo=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function VT(r){return r?.reason!==null}var Gr=class extends Wo{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,It.ProtocolError),this.name="InvalidFrameError"}},tl=class extends Wo{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,It.ProtocolError),this.name="UnRequestedPingError"}},rl=class extends Wo{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,It.ProtocolError),this.name="NotMatchingPingError"}};var Y0=class extends Wo{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,It.ProtocolError),this.name="StreamAlreadyExistsError"}},X0=class extends Wo{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,It.ProtocolError),this.name="DecodeInvalidVersionError"}},Q0=class extends Wo{static name="BothClientsError";constructor(e="Both clients"){super(e,It.ProtocolError),this.name="BothClientsError"}},nl=class extends Wo{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,It.ProtocolError),this.name="ReceiveWindowExceededError"}};var e8e=new Set([Gr.name,tl.name,rl.name,Y0.name,X0.name,Q0.name,nl.name]),cf=256*1024,J0=16*1024*1024;var lf={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:cf,maxStreamWindowSize:J0,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function HT(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new A("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new A("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new A("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new A("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<cf)throw new A("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new A("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new A("MaxStreamWindowSize must be less than equal MAX_UINT32")}function zT(r){return r.header.type===nt.Data&&r.data!==null}var qT=2**24;function IV(r){if(r[0]!==KT)throw new Gr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*qT+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*qT+(r[9]<<16)+(r[10]<<8)+r[11]}}var Z0=class{buffer;constructor(){this.buffer=new el}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=to;if(this.buffer.byteLength<to)return;let t=IV(this.buffer.subarray(0,to));if(t.type===nt.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(to,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function y5(r){let e=new Uint8Array(to);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var mr;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(mr||(mr={}));var e2=class extends ds{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??cf;super({...e,maxMessageSize:t-to}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??J0,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=mr.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let s=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,s);e.consume(s);let c=this.sendFrame({type:nt.Data,flag:i,streamID:this.streamId,length:s},a);if(this.sendWindowCapacity-=s,n+=s,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:nt.WindowUpdate,flag:ke.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|ke.FIN;this.sendFrame({type:nt.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=mr.Paused}sendResume(){this.state=mr.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-to,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!zT(e))throw new Gr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new nl("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&ke.ACK)===ke.ACK&&this.state===mr.SYNSent&&(this.state=mr.Established),(e&ke.FIN)===ke.FIN&&this.onRemoteCloseWrite(),(e&ke.RST)===ke.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case mr.Init:return this.state=mr.SYNSent,ke.SYN;case mr.SYNReceived:return this.state=mr.Established,ke.ACK;default:return 0}}sendWindowUpdate(){if(this.state===mr.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:nt.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function WT(r){return{type:nt[r.type],flags:[(r.flag&ke.SYN)===ke.SYN?"SYN":void 0,(r.flag&ke.ACK)===ke.ACK?"ACK":void 0,(r.flag&ke.FIN)===ke.FIN?"FIN":void 0,(r.flag&ke.RST)===ke.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var GT="/yamux/1.0.0",t2=class{protocol=GT;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[xe]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new w5(e,{...this._init})}},w5=class extends us{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:GT,name:"yamux"}),this.client=e.direction==="outbound",HT(t),this.enableKeepAlive=t.enableKeepAlive??lf.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??lf.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??lf.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??lf.maxOutboundStreams,this.decoder=new Z0,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=oc(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new an("Muxer closed remotely");if(this.localGoAway!==void 0)throw new an("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Sa("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,mr.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new an("Muxer closed remotely");if(this.localGoAway!==void 0)throw new an("Muxer closed locally");if(this.activePing!=null)return Ue(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await Ue(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??It.NormalTermination;this.log.trace("muxer close reason=%s",It[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=It.InternalError;VT(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(s=>s.streamId===e)!=null)throw new A("Stream already exists with that id");let o=new e2({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",WT(e.header)),t===0)switch(n){case nt.Ping:{this.handlePing(e.header);return}case nt.GoAway:{this.handleGoAway(o);return}default:throw new Gr("Invalid frame type")}else switch(e.header.type){case nt.Data:case nt.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new Gr("Invalid frame type")}}handlePing(e){if(e.flag===ke.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,ke.ACK);else if(e.flag===ke.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new Gr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new tl("ping not requested");if(this.activePing.id!==e)throw new rl("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",It[e]??"unknown"),this.remoteGoAway=e,e===It.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&ke.SYN)===ke.SYN&&this.incomingStream(t);let s=this.streams.find(i=>i.streamId===t);if(s===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case nt.WindowUpdate:{s.handleWindowUpdate(e);return}case nt.Data:{s.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new A("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:nt.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:nt.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}let t=this._newStream(e,mr.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===nt.Data){if(t==null)throw new Gr("Invalid frame");n=new el(y5(e),t)}else n=y5(e);return this.log.trace("sending frame %o",WT(e)),this.send(n)}sendPing(e,t=ke.SYN){t===ke.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:nt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=It.NormalTermination){this.log("sending GoAway reason=%s",It[e]),this.localGoAway=e,this.sendFrame({type:nt.GoAway,flag:0,streamID:0,length:e})}};function jT(r={}){return()=>new t2(r)}var YT="libp2p",XT="autonat",QT="1.0.0";var Qe;(function(r){let e;(function(f){f.DIAL="DIAL",f.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(f){f[f.DIAL=0]="DIAL",f[f.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(f){f.codec=()=>et(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(f){f.OK="OK",f.E_DIAL_ERROR="E_DIAL_ERROR",f.E_DIAL_REFUSED="E_DIAL_REFUSED",f.E_BAD_REQUEST="E_BAD_REQUEST",f.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(f){f[f.OK=0]="OK",f[f.E_DIAL_ERROR=100]="E_DIAL_ERROR",f[f.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",f[f.E_BAD_REQUEST=200]="E_BAD_REQUEST",f[f.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(f){f.codec=()=>et(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(f){let h;f.codec=()=>(h==null&&(h=ae((m,w,x={})=>{if(x.lengthDelimited!==!1&&w.fork(),m.id!=null&&(w.uint32(10),w.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let E of m.addrs)w.uint32(18),w.bytes(E);x.lengthDelimited!==!1&&w.ldelim()},(m,w,x={})=>{let E={addrs:[]},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{E.id=m.bytes();break}case 2:{if(x.limits?.addrs!=null&&E.addrs.length===x.limits.addrs)throw new he('Decode error - repeated field "addrs" had too many elements');E.addrs.push(m.bytes());break}default:{m.skipType(T&7);break}}}return E},function*(m,w,x,E={}){let S={addrs:0},T=w==null?m.len:m.pos+w;for(;m.pos<T;){let I=m.uint32();switch(I>>>3){case 1:{yield{field:`${x}.id`,value:m.bytes()};break}case 2:{if(E.limits?.addrs!=null&&S.addrs===E.limits.addrs)throw new he('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${x}.addrs[]`,index:S.addrs,value:m.bytes()},S.addrs++;break}default:{m.skipType(I&7);break}}}})),h);function p(m){return se(m,f.codec())}f.encode=p;function y(m,w){return oe(m,f.codec(),w)}f.decode=y;function g(m,w){return ie(m,f.codec(),w)}f.stream=g})(s=r.PeerInfo||(r.PeerInfo={}));let i;(function(f){let h;f.codec=()=>(h==null&&(h=ae((m,w,x={})=>{x.lengthDelimited!==!1&&w.fork(),m.peer!=null&&(w.uint32(10),r.PeerInfo.codec().encode(m.peer,w)),x.lengthDelimited!==!1&&w.ldelim()},(m,w,x={})=>{let E={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?E.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:x.limits?.peer}):m.skipType(T&7)}return E},function*(m,w,x,E={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${x}.peer`,{limits:E.limits?.peer}):m.skipType(T&7)}})),h);function p(m){return se(m,f.codec())}f.encode=p;function y(m,w){return oe(m,f.codec(),w)}f.decode=y;function g(m,w){return ie(m,f.codec(),w)}f.stream=g})(i=r.Dial||(r.Dial={}));let a;(function(f){let h;f.codec=()=>(h==null&&(h=ae((m,w,x={})=>{x.lengthDelimited!==!1&&w.fork(),m.status!=null&&(w.uint32(8),r.ResponseStatus.codec().encode(m.status,w)),m.statusText!=null&&(w.uint32(18),w.string(m.statusText)),m.addr!=null&&(w.uint32(26),w.bytes(m.addr)),x.lengthDelimited!==!1&&w.ldelim()},(m,w,x={})=>{let E={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{E.status=r.ResponseStatus.codec().decode(m);break}case 2:{E.statusText=m.string();break}case 3:{E.addr=m.bytes();break}default:{m.skipType(T&7);break}}}return E},function*(m,w,x,E={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{yield{field:`${x}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${x}.statusText`,value:m.string()};break}case 3:{yield{field:`${x}.addr`,value:m.bytes()};break}default:{m.skipType(T&7);break}}}})),h);function p(m){return se(m,f.codec())}f.encode=p;function y(m,w){return oe(m,f.codec(),w)}f.decode=y;function g(m,w){return ie(m,f.codec(),w)}f.stream=g})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=ae((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.type!=null&&(h.uint32(8),r.MessageType.codec().encode(f.type,h)),f.dial!=null&&(h.uint32(18),r.Dial.codec().encode(f.dial,h)),f.dialResponse!=null&&(h.uint32(26),r.DialResponse.codec().encode(f.dialResponse,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.type=r.MessageType.codec().decode(f);break}case 2:{y.dial=r.Dial.codec().decode(f,f.uint32(),{limits:p.limits?.dial});break}case 3:{y.dialResponse=r.DialResponse.codec().decode(f,f.uint32(),{limits:p.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.type`,value:r.MessageType.codec().decode(f)};break}case 2:{yield*r.Dial.codec().stream(f,f.uint32(),`${p}.dial`,{limits:y.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(f,f.uint32(),`${p}.dialResponse`,{limits:y.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return se(f,r.codec())}r.encode=l;function u(f,h){return oe(f,r.codec(),h)}r.decode=u;function d(f,h){return ie(f,r.codec(),h)}r.stream=d})(Qe||(Qe={}));var LV=4,DV=8,r2=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??YT}/${XT}/${QT}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=gt({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=oc(this.findRandomPeers.bind(this),6e4),this.addressFilter=Nt(1024)}[Symbol.toStringTag]="@libp2p/autonat";[xe]=["@libp2p/autonat"];get[kr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=de([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=We(e,{maxDataLength:this.maxMessageSize}).pb(Qe),s=await o.read({signal:n}),i=await this.handleAutonatMessage(s,t,{signal:n});await o.write(i,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>ce(d).host),s=e.dial;if(s==null)return this.log.error("dial was missing from message"),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let i,a=s.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=Ee(a.id);i=wt(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",i),!t.remotePeer.equals(i))return this.log("target peer %p did not equal sending peer %p",i,t.remotePeer),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>G(d)).filter(d=>{try{let f=ce(d);return it(d)?!1:f.host!==ce(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(f.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(f=>f.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${i.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",i),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),i);let l="",u=c[0];for(let d of c){let f;u=d;try{if(f=await this.components.connectionManager.openConnection(d,n),!f.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,f.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",i,d),{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.OK,addr:f.remoteAddr.decapsulateCode(421).bytes}}}catch(h){this.log.error("could not dial %p - %e",i,h),l=h.message}finally{f!=null&&await f.close()}}return{type:Qe.MessageType.DIAL_RESPONSE,dialResponse:{status:Qe.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,s)=>o.type==="observed"&&s.type!=="observed"?1:s.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||ce(o.multiaddr).type==="ip6"&&(!t||!Bh(o.multiaddr))||it(o.multiaddr)));for(let o of n){let s=o.multiaddr.toString(),i=this.dialResults.get(s);if(i!=null){if(i.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",i.multiaddr,e);continue}if(i.queue.size>10){this.log.trace("%a already has enough peers queued",i.multiaddr);continue}}if(i==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(s),this.addressFilter.has(s))continue;this.addressFilter.add(s),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",s),i={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:cy(),queue:new Xt({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(s,i)}return i}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:i})=>ce(i).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),s=this.getFirstUnverifiedMultiaddr(o,n);if(s==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){s.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s.multiaddr),this.confirmAddress(s)):this.log("skipping verifying %a because we are too close to the connection limit",s.multiaddr);return}s.queue.add(async i=>{await this.askPeerToVerify(e,o,i)},{peerId:e.remotePeer,multiaddr:s.multiaddr}).catch(i=>{s?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,s?.multiaddr,i)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let s=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let i=await e.newStream(this.protocol,{signal:s});try{let a=We(i).pb(Qe),[,c]=await Promise.all([a.write({type:Qe.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:s}),a.read({signal:s})]);if(c.type!==Qe.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Qe.ResponseStatus.OK&&l!==Qe.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Qe.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Qe.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===LV&&this.confirmAddress(o),o.failure===DV&&this.unconfirmAddress(o)}finally{try{await i.close({signal:s})}catch(a){i.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=ce(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new A(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function JT(r={}){return e=>new r2(e,r)}var RV="bootstrap",NV=50,OV=1e3,b5=class extends le{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??OV,this.list=t.list.map(n=>G(n)).filter(n=>Ha.matches(n)?n.getComponents().findLast(s=>s.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:Xe(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[ii]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[xe]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??RV]:{value:this._init.tagValue??NV,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function ZT(r){return e=>new b5(e,r)}var x5=1e3,eC=60*x5;var e5e=120*eC,tC=1,n2=5e3,rC=100;var uf=`${ci}-circuit-relay`,t5e=2*eC,r5e=BigInt(1<<17),fa="/libp2p/circuit/relay/0.2.0/hop",E5="/libp2p/circuit/relay/0.2.0/stop",n5e=30*x5,o5e=30*x5,v5=300,nC=4096,oC=.001;var Us;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>et(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Bs.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),df.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Ms.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),Tt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Bs.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=df.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Ms.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=Tt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Bs.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*df.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Ms.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:Tt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Us||(Us={}));var ro;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>et(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Bs.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Ms.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),Tt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Bs.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Ms.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=Tt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Bs.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Ms.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:Tt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(ro||(ro={}));var Bs;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.id!=null&&s.id.byteLength>0&&(i.uint32(10),i.bytes(s.id)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={id:me(0),addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.id=s.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new he('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:s.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new he('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Bs||(Bs={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.expire!=null&&s.expire!==0n&&(i.uint32(8),i.uint64(s.expire)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);s.voucher!=null&&(i.uint32(26),hf.codec().encode(s.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.expire=s.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new he('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 3:{c.voucher=hf.codec().decode(s,s.uint32(),{limits:a.limits?.voucher});break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.expire`,value:s.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new he('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}case 3:{yield*hf.codec().stream(s,s.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{s.skipType(d&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(df||(df={}));var Ms;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.duration!=null&&(i.uint32(8),i.uint32(s.duration)),s.data!=null&&(i.uint32(16),i.uint64(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.duration=s.uint32();break}case 2:{c.data=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:s.uint32()};break}case 2:{yield{field:`${a}.data`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(Ms||(Ms={}));var Tt;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Tt||(Tt={}));var S5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(S5||(S5={}));(function(r){r.codec=()=>et(S5)})(Tt||(Tt={}));var ff;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.relay!=null&&s.relay.byteLength>0&&(i.uint32(10),i.bytes(s.relay)),s.peer!=null&&s.peer.byteLength>0&&(i.uint32(18),i.bytes(s.peer)),s.expiration!=null&&s.expiration!==0n&&(i.uint32(24),i.uint64(s.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={relay:me(0),peer:me(0),expiration:0n},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.relay=s.bytes();break}case 2:{c.peer=s.bytes();break}case 3:{c.expiration=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:s.bytes()};break}case 2:{yield{field:`${a}.peer`,value:s.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(ff||(ff={}));var hf;(function(r){let e;r.codec=()=>(e==null&&(e=ae((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&(i.uint32(26),ff.codec().encode(s.payload,i)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:me(0),payloadType:me(0),signature:me(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=ff.codec().decode(s,s.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield*ff.codec().stream(s,s.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return se(s,r.codec())}r.encode=t;function n(s,i){return oe(s,r.codec(),i)}r.decode=n;function o(s,i){return ie(s,r.codec(),i)}r.stream=o})(hf||(hf={}));var pf=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},o2=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},s2=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function A5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var mf=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},i2=Re(Se(Ha.matchers[0],De(290))),a2=Re(De(290));var c2=class extends le{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(fa,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(fa)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=sC(n),i=sC(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Xt({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=de([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function sC(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(M(e)).getTime()}var I5=class extends le{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??n2,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(a2.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(i2.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new si(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>G(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function iC(r){return new I5(r)}var aC="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var cC=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=aC[t[r]&63];return e};var BV=60*1e3*10,MV=60*1e3*5,UV=30*1e3,l2=class extends le{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Jt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??rC,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??n2,this.started=!1,this.relayFilter=Nt(100),this.reserveQueue=new Xt({concurrency:t?.reservationConcurrency??tC,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(uf)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[uf]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=cC();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new si("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new s2("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new si("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let p=this.connectionManager.getConnections(e),y=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(g=>g.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),y=!0),y&&A5(s.reservation.expire)>BV)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new pf("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(_t.matches(a.remoteAddr))throw new o2("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=A5(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-MV,UV),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new pf("Made reservation on relay but did not need any more discovered relays");f={timeout:d,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[uf]:{value:1,ttl:l}}}),this.#r();let h={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(fa,t),s=We(n).pb(Us);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Us.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===Tt.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=G(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=G(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>G(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[uf]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Nt(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var T5=class extends ls{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function C5(r){return new T5(r)}var FV=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(G)}catch{return!1}return!0},lC={maxInboundStopStreams:v5,maxOutboundStopStreams:v5,stopTimeout:3e4},u2=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??lC.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??lC.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new c2(e,{filter:t.discoveryFilter??ly(nC,oC)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new l2(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[xe]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[kr](){return this.discovery!=null?["@libp2p/identify"]:[]}[ts]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(E5,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await ht(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ct(this.discovery,this.reservationStore),await this.components.registrar.unhandle(E5),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=G(n[0]),s=G(n[n.length-1]),i=o.getComponents().find(h=>h.code===421)?.value,a=s.getComponents().find(h=>h.code===421)?.value;if(i==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new Zo(`C${h}`)}let c=Xe(i),l=Xe(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new R("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new R("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new R("circuit-relay:open-hop-stream")),f=await d.newStream(fa,t);let h=We(f).pb(Us);t.onProgress?.(new R("circuit-relay:write-connect-message")),await h.write({type:Us.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[G(s).bytes]}},t),t.onProgress?.(new R("circuit-relay:read-connect-response"));let p=await h.read(t);if(p.status!==Tt.OK)throw new pe(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new mf(p.limit),g=C5({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:y.onData,onDataWrite:y.onData,log:f.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(g,{...t,limits:y.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,p.limit??"none",d.id),m}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,h),f?.abort(h),h}}createListener(e){return iC({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>i2.exactMatch(t)||a2.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>_t.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=We(e).pb(ro),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==ro.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!FV(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=wt(Ee(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:ro.Type.STATUS,status:Tt.OK},{signal:n});let a=new mf(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=C5({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function uC(r={}){return e=>new u2(e,r)}var Ln;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>et(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ae((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new he('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new he('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(h&7);break}}}})),n);function o(a){return se(a,r.codec())}r.encode=o;function s(a,c){return oe(a,r.codec(),c)}r.decode=s;function i(a,c){return ie(a,r.codec(),c)}r.stream=i})(Ln||(Ln={}));function k5(r,e){return _t.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:Xh.matches(r)?!0:B9.matches(r)?!it(r):!1}var dC=1024*4,fC=100,d2={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},f2=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??d2.timeout,this.retries=t.retries??d2.retries,this.maxInboundStreams=t.maxInboundStreams??d2.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??d2.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[kr]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(gf,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{_t.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(gf,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(gf),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([gf],{signal:o.signal,runOnLimitedConnection:!0});let s=We(t,{maxDataLength:dC}).pb(Ln);this.log("B sending connect to %p",e.remotePeer);let i=Date.now();await s.write({type:Ln.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await s.read(o);if(a.type!==Ln.Type.CONNECT)throw this.log("A sent wrong message type"),new pe("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new pe("DCUtR connect message had no multiaddrs");let l=Date.now()-i;this.log("A sending sync, rtt %dms",l),await s.write({type:Ln.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await hE(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:fC,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(s){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let s=o.multiaddr;return s.getComponents().find(i=>i.code===421)?.value==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(o=>k5(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(_t.exactMatch(s.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close({signal:o}),!0}catch(s){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,s)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=We(e,{maxDataLength:dC}).pb(Ln);this.log("A receiving connect");let s=await o.read(n);if(s.type!==Ln.Type.CONNECT)throw this.log("B sent wrong message type"),new pe("DCUtR message type was incorrect");if(s.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new pe("DCUtR connect message had no multiaddrs");let i=this.getDialableMultiaddrs(s.observedAddresses);if(i.length===0)throw this.log("B had no dialable multiaddrs in %o",s.observedAddresses.map(l=>G(l))),new pe("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:Ln.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==Ln.Type.SYNC)throw new pe("DCUtR message type was incorrect");this.log("A dialing",i);let c=await this.connectionManager.openConnection(i,{signal:n.signal,priority:fC,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=G(n);if(!k5(o,this.transportManager))continue;t.push(o)}catch{}return t}};var gf="/libp2p/dcutr";function hC(r={}){return e=>new f2(e,r)}var R5={};V(R5,{base10:()=>WV});var C7e=new Uint8Array(0);function pC(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 Go(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function mC(r){return new TextEncoder().encode(r)}function gC(r){return new TextDecoder().decode(r)}function $V(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,y++;for(var x=(w-m)*u+1>>>0,E=new Uint8Array(x);m!==w;){for(var S=p[m],T=0,I=x-1;(S!==0||T<g)&&I!==-1;I--,T++)S+=256*E[I]>>>0,E[I]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");g=T,m++}for(var C=x-g;C!==x&&E[C]===0;)C++;for(var U=c.repeat(y);C<x;++C)U+=r.charAt(E[C]);return U}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var w=(p.length-y)*l+1>>>0,x=new Uint8Array(w);p[y];){var E=t[p.charCodeAt(y)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<m)&&T!==-1;T--,S++)E+=a*x[T]>>>0,x[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");m=S,y++}if(p[y]!==" "){for(var I=w-m;I!==w&&x[I]===0;)I++;for(var C=new Uint8Array(g+(w-I)),U=g;I!==w;)C[U++]=x[I++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var KV=$V,VV=KV,wC=VV;var _5=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")}},P5=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bC(this,e)}},L5=class{decoders;constructor(e){this.decoders=e}or(e){return bC(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 bC(r,e){return new L5({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var D5=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new _5(e,t,n),this.decoder=new P5(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ol({name:r,prefix:e,encode:t,decode:n}){return new D5(r,e,t,n)}function Fs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=wC(t,r);return ol({prefix:e,name:r,encode:n,decode:s=>Go(o(s))})}function HV(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function qV(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function zV(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function lt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=zV(n);return ol({prefix:e,name:r,encode(s){return qV(s,n,t)},decode(s){return HV(s,o,t,r)}})}var WV=Fs({prefix:"9",name:"base10",alphabet:"0123456789"});var N5={};V(N5,{base16:()=>GV,base16upper:()=>jV});var GV=lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),jV=lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var O5={};V(O5,{base2:()=>YV});var YV=lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var B5={};V(B5,{base256emoji:()=>eH});var xC=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}"),XV=xC.reduce((r,e,t)=>(r[t]=e,r),[]),QV=xC.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function JV(r){return r.reduce((e,t)=>(e+=XV[t],e),"")}function ZV(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=QV[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var eH=ol({prefix:"\u{1F680}",name:"base256emoji",encode:JV,decode:ZV});var M5={};V(M5,{base32:()=>sl,base32hex:()=>oH,base32hexpad:()=>iH,base32hexpadupper:()=>aH,base32hexupper:()=>sH,base32pad:()=>rH,base32padupper:()=>nH,base32upper:()=>tH,base32z:()=>cH});var sl=lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tH=lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rH=lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nH=lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),oH=lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sH=lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),iH=lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),aH=lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cH=lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var U5={};V(U5,{base36:()=>yf,base36upper:()=>lH});var yf=Fs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lH=Fs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var F5={};V(F5,{base58btc:()=>no,base58flickr:()=>uH});var no=Fs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uH=Fs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $5={};V($5,{base64:()=>dH,base64pad:()=>fH,base64url:()=>hH,base64urlpad:()=>pH});var dH=lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fH=lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hH=lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pH=lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var K5={};V(K5,{base8:()=>mH});var mH=lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var V5={};V(V5,{identity:()=>gH});var gH=ol({prefix:"\0",name:"identity",encode:r=>gC(r),decode:r=>mC(r)});var H7e=new TextEncoder,q7e=new TextDecoder;var q5={};V(q5,{identity:()=>FH});var bH=SC,EC=128,xH=127,EH=~xH,vH=Math.pow(2,31);function SC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vH;)e[t++]=r&255|EC,r/=128;for(;r&EH;)e[t++]=r&255|EC,r>>>=7;return e[t]=r|0,SC.bytes=t-n+1,e}var SH=H5,AH=128,vC=127;function H5(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw H5.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&vC)<<o:(i&vC)*Math.pow(2,o),o+=7}while(i>=AH);return H5.bytes=s-n,t}var IH=Math.pow(2,7),TH=Math.pow(2,14),CH=Math.pow(2,21),kH=Math.pow(2,28),_H=Math.pow(2,35),PH=Math.pow(2,42),LH=Math.pow(2,49),DH=Math.pow(2,56),RH=Math.pow(2,63),NH=function(r){return r<IH?1:r<TH?2:r<CH?3:r<kH?4:r<_H?5:r<PH?6:r<LH?7:r<DH?8:r<RH?9:10},OH={encode:bH,decode:SH,encodingLength:NH},BH=OH,wf=BH;function bf(r,e=0){return[wf.decode(r,e),wf.decode.bytes]}function il(r,e,t=0){return wf.encode(r,e,t),e}function al(r){return wf.encodingLength(r)}function ll(r,e){let t=e.byteLength,n=al(r),o=n+al(t),s=new Uint8Array(o+t);return il(r,s,0),il(t,s,n),s.set(e,o),new cl(r,t,e,s)}function AC(r){let e=Go(r),[t,n]=bf(e),[o,s]=bf(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cl(t,o,i,e)}function IC(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pC(r.bytes,t.bytes)}}var cl=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var TC=0,MH="identity",CC=Go;function UH(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 ll(TC,CC(r))}var FH={code:TC,name:MH,encode:CC,digest:UH};var G5={};V(G5,{sha256:()=>KH,sha512:()=>VH});var $H=20;function W5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new z5(r,e,t,n,o)}var z5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??$H,this.maxDigestLength=s}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?kC(n,this.code,t?.truncate):n.then(o=>kC(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function kC(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 ll(e,r)}function PC(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var KH=W5({name:"sha2-256",code:18,encode:PC("SHA-256")}),VH=W5({name:"sha2-512",code:19,encode:PC("SHA-512")});function LC(r,e){let{bytes:t,version:n}=r;return n===0?qH(t,j5(r),e??no.encoder):zH(t,j5(r),e??sl.encoder)}var DC=new WeakMap;function j5(r){let e=DC.get(r);if(e==null){let t=new Map;return DC.set(r,t),t}return e}var p2=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ef)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==WH)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=ll(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&&IC(e.multihash,n.multihash)}toString(e){return LC(this,e)}toJSON(){return{"/":LC(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??RC(n,o,s.bytes))}else if(t[GH]===!0){let{version:n,multihash:o,code:s}=t,i=AC(o);return r.create(n,s,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!==Ef)throw new Error(`Version 0 CID must use dag-pb (code: ${Ef}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=RC(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ef,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Go(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new cl(t.multihashCode,t.digestSize,s,o);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]=bf(e.subarray(t));return t+=f,d},o=n(),s=Ef;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=HH(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return j5(s).set(n,e),s}};function HH(r,e){switch(r[0]){case"Q":{let t=e??no;return[no.prefix,t.decode(`${no.prefix}${r}`)]}case no.prefix:{let t=e??no;return[no.prefix,t.decode(r)]}case sl.prefix:{let t=e??sl;return[sl.prefix,t.decode(r)]}case yf.prefix:{let t=e??yf;return[yf.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 qH(r,e,t){let{prefix:n}=t;if(n!==no.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function zH(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ef=112,WH=18;function RC(r,e,t){let n=al(r),o=n+al(e),s=new Uint8Array(o+t.byteLength);return il(r,s,0),il(e,s,n),s.set(t,o),s}var GH=Symbol.for("@ipld/js-cid/CID");var Y5={...V5,...O5,...K5,...R5,...N5,...M5,...U5,...F5,...$5,...B5},fwe={...G5,...q5};function NC(r=0){return new Uint8Array(r)}function BC(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var OC=BC("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),X5=BC("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=NC(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jH={utf8:OC,"utf-8":OC,hex:Y5.base16,latin1:X5,ascii:X5,binary:X5,...Y5},MC=jH;function Q5(r,e="utf8"){let t=MC[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Q(r){if(r!==void 0&&r!==Q.REQUEST&&r!==Q.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");r===void 0||this.initialize(r),this.maxHeaderSize=Q.maxHeaderSize}Q.prototype.initialize=function(r,e){if(r!==Q.REQUEST&&r!==Q.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");this.type=r,this.state=r+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1};Q.encoding="ascii";Q.maxHeaderSize=80*1024;Q.REQUEST="REQUEST";Q.RESPONSE="RESPONSE";var UC=Q.kOnHeaders=1,J5=Q.kOnHeadersComplete=2,m2=Q.kOnBody=3,Z5=Q.kOnMessageComplete=4;Q.prototype[UC]=Q.prototype[J5]=Q.prototype[m2]=Q.prototype[Z5]=function(){};var FC=!0;Object.defineProperty(Q,"kOnExecute",{get:function(){return FC=!1,99}});var $C=Q.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK","SOURCE"],KC=$C.indexOf("CONNECT");Q.prototype.reinitialize=Q;Q.prototype.close=Q.prototype.pause=Q.prototype.resume=Q.prototype.remove=Q.prototype.free=function(){};Q.prototype._compatMode0_11=!1;Q.prototype.getAsyncId=function(){return 0};var YH={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};Q.prototype.execute=function(r,e,t){if(!(this instanceof Q))throw new TypeError("not a HTTPParser");e=e||0,t=typeof t=="number"?t:r.length,this.chunk=r,this.offset=e;var n=this.end=e+t;try{for(;this.offset<n&&!this[this.state](););}catch(o){if(this.isUserCall)throw o;return this.hadError=!0,o}return this.chunk=null,t=this.offset-e,YH[this.state]&&(this.headerSize+=t,this.headerSize>(this.maxHeaderSize||Q.maxHeaderSize))?new Error("max header size exceeded"):t};var XH={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};Q.prototype.finish=function(){if(!this.hadError){if(!XH[this.state])return new Error("invalid state for EOF");this.state==="BODY_RAW"&&this.userCall()(this[Z5]())}};Q.prototype.consume=Q.prototype.unconsume=Q.prototype.getCurrentBuffer=function(){};Q.prototype.userCall=function(){this.isUserCall=!0;var r=this;return function(e){return r.isUserCall=!1,e}};Q.prototype.nextRequest=function(){this.userCall()(this[Z5]()),this.reinitialize(this.type)};Q.prototype.consumeLine=function(){for(var r=this.end,e=this.chunk,t=this.offset;t<r;t++)if(e[t]===10){var n=this.line+Q5(e.subarray(this.offset,t),Q.encoding);return n.charAt(n.length-1)==="\r"&&(n=n.substr(0,n.length-1)),this.line="",this.offset=t+1,n}this.line+=Q5(e.subarray(this.offset,this.end),Q.encoding),this.offset=this.end};var QH=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,JH=/^[ \t]+(.*[^ \t])/;Q.prototype.parseHeader=function(r,e){if(r.indexOf("\r")!==-1)throw g2("HPE_LF_EXPECTED");var t=QH.exec(r),n=t&&t[1];if(n)e.push(n),e.push(t[2]);else{var o=JH.exec(r);o&&e.length&&(e[e.length-1]&&(e[e.length-1]+=" "),e[e.length-1]+=o[1])}};var ZH=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;Q.prototype.REQUEST_LINE=function(){var r=this.consumeLine();if(r){var e=ZH.exec(r);if(e===null)throw g2("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?e[1]:$C.indexOf(e[1]),this.info.method===-1)throw new Error("invalid request method");this.info.url=e[2],this.info.versionMajor=+e[3],this.info.versionMinor=+e[4],this.body_bytes=0,this.state="HEADER"}};var eq=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;Q.prototype.RESPONSE_LINE=function(){var r=this.consumeLine();if(r){var e=eq.exec(r);if(e===null)throw g2("HPE_INVALID_CONSTANT");this.info.versionMajor=+e[1],this.info.versionMinor=+e[2];var t=this.info.statusCode=+e[3];this.info.statusMessage=e[4],((t/100|0)===1||t===204||t===304)&&(this.body_bytes=0),this.state="HEADER"}};Q.prototype.shouldKeepAlive=function(){if(this.info.versionMajor>0&&this.info.versionMinor>0){if(this.connection.indexOf("close")!==-1)return!1}else if(this.connection.indexOf("keep-alive")===-1)return!1;return!!(this.body_bytes!==null||this.isChunked)};Q.prototype.HEADER=function(){var r=this.consumeLine();if(r!==void 0){var e=this.info;if(r)this.parseHeader(r,e.headers);else{for(var t=e.headers,n=!1,o,s=!1,i=0;i<t.length;i+=2)switch(t[i].toLowerCase()){case"transfer-encoding":this.isChunked=t[i+1].toLowerCase()==="chunked";break;case"content-length":if(o=+t[i+1],n){if(o!==this.body_bytes)throw g2("HPE_UNEXPECTED_CONTENT_LENGTH")}else n=!0,this.body_bytes=o;break;case"connection":this.connection+=t[i+1].toLowerCase();break;case"upgrade":s=!0;break}this.isChunked&&n&&(n=!1,this.body_bytes=null),s&&this.connection.indexOf("upgrade")!=-1?e.upgrade=this.type===Q.REQUEST||e.statusCode===101:e.upgrade=e.method===KC,this.isChunked&&e.upgrade&&(this.isChunked=!1),e.shouldKeepAlive=this.shouldKeepAlive();var a;if(FC?a=this.userCall()(this[J5](e)):a=this.userCall()(this[J5](e.versionMajor,e.versionMinor,e.headers,e.method,e.url,e.statusCode,e.statusMessage,e.upgrade,e.shouldKeepAlive)),a===2)return this.nextRequest(),!0;if(this.isChunked&&!a)this.state="BODY_CHUNKHEAD";else{if(a||this.body_bytes===0)return this.nextRequest(),e.upgrade;this.body_bytes===null?this.state="BODY_RAW":this.state="BODY_SIZED"}}}};Q.prototype.BODY_CHUNKHEAD=function(){var r=this.consumeLine();r!==void 0&&(this.body_bytes=parseInt(r,16),this.body_bytes?this.state="BODY_CHUNK":this.state="BODY_CHUNKTRAILERS")};Q.prototype.BODY_CHUNK=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[m2](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")};Q.prototype.BODY_CHUNKEMPTYLINE=function(){var r=this.consumeLine();if(r!==void 0){if(r!=="")throw new Error("Expected empty line");this.state="BODY_CHUNKHEAD"}};Q.prototype.BODY_CHUNKTRAILERS=function(){var r=this.consumeLine();r!==void 0&&(r?this.parseHeader(r,this.trailers):(this.trailers.length&&this.userCall()(this[UC](this.trailers,"")),this.nextRequest()))};Q.prototype.BODY_RAW=function(){this.userCall()(this[m2](this.chunk.slice(this.offset,this.end),0,this.end-this.offset)),this.offset=this.end};Q.prototype.BODY_SIZED=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[m2](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||this.nextRequest()};["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(r){var e=Q["kOn"+r];Object.defineProperty(Q.prototype,"on"+r,{get:function(){return this[e]},set:function(t){return this._compatMode0_11=!0,KC="CONNECT",this[e]=t}})});function g2(r){var e=new Error("Parse Error");return e.code=r,e}function VC(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function e7(r,e={}){let t=VC(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:s,done:i}=await t.next();if(this._cancelled)return;if(i===!0){o.close();return}o.enqueue(s)}catch(s){o.error(s)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var tq=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),HC=jl({name:"sha-1",code:17,encode:tq("SHA-1")});var s7={};V(s7,{base10:()=>cq});var Cwe=new Uint8Array(0);function qC(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 jo(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function zC(r){return new TextEncoder().encode(r)}function WC(r){return new TextDecoder().decode(r)}function rq(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,y++;for(var x=(w-m)*u+1>>>0,E=new Uint8Array(x);m!==w;){for(var S=p[m],T=0,I=x-1;(S!==0||T<g)&&I!==-1;I--,T++)S+=256*E[I]>>>0,E[I]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");g=T,m++}for(var C=x-g;C!==x&&E[C]===0;)C++;for(var U=c.repeat(y);C<x;++C)U+=r.charAt(E[C]);return U}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var w=(p.length-y)*l+1>>>0,x=new Uint8Array(w);p[y];){var E=t[p.charCodeAt(y)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<m)&&T!==-1;T--,S++)E+=a*x[T]>>>0,x[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");m=S,y++}if(p[y]!==" "){for(var I=w-m;I!==w&&x[I]===0;)I++;for(var C=new Uint8Array(g+(w-I)),U=g;I!==w;)C[U++]=x[I++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var nq=rq,oq=nq,jC=oq;var t7=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")}},r7=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return YC(this,e)}},n7=class{decoders;constructor(e){this.decoders=e}or(e){return YC(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 YC(r,e){return new n7({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var o7=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new t7(e,t,n),this.decoder=new r7(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ul({name:r,prefix:e,encode:t,decode:n}){return new o7(r,e,t,n)}function $s({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=jC(t,r);return ul({prefix:e,name:r,encode:n,decode:s=>jo(o(s))})}function sq(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function iq(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function aq(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ut({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=aq(n);return ul({prefix:e,name:r,encode(s){return iq(s,n,t)},decode(s){return sq(s,o,t,r)}})}var cq=$s({prefix:"9",name:"base10",alphabet:"0123456789"});var i7={};V(i7,{base16:()=>lq,base16upper:()=>uq});var lq=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),uq=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var a7={};V(a7,{base2:()=>dq});var dq=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var c7={};V(c7,{base256emoji:()=>gq});var XC=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}"),fq=XC.reduce((r,e,t)=>(r[t]=e,r),[]),hq=XC.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function pq(r){return r.reduce((e,t)=>(e+=fq[t],e),"")}function mq(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=hq[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var gq=ul({prefix:"\u{1F680}",name:"base256emoji",encode:pq,decode:mq});var l7={};V(l7,{base32:()=>dl,base32hex:()=>xq,base32hexpad:()=>vq,base32hexpadupper:()=>Sq,base32hexupper:()=>Eq,base32pad:()=>wq,base32padupper:()=>bq,base32upper:()=>yq,base32z:()=>Aq});var dl=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yq=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wq=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bq=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xq=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eq=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),vq=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sq=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Aq=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var u7={};V(u7,{base36:()=>vf,base36upper:()=>Iq});var vf=$s({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iq=$s({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var d7={};V(d7,{base58btc:()=>oo,base58flickr:()=>Tq});var oo=$s({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tq=$s({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var f7={};V(f7,{base64:()=>Cq,base64pad:()=>kq,base64url:()=>_q,base64urlpad:()=>Pq});var Cq=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kq=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_q=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Pq=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var h7={};V(h7,{base8:()=>Lq});var Lq=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var p7={};V(p7,{identity:()=>Dq});var Dq=ul({prefix:"\0",name:"identity",encode:r=>WC(r),decode:r=>zC(r)});var Hwe=new TextEncoder,qwe=new TextDecoder;var g7={};V(g7,{identity:()=>tz});var Oq=ZC,QC=128,Bq=127,Mq=~Bq,Uq=Math.pow(2,31);function ZC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Uq;)e[t++]=r&255|QC,r/=128;for(;r&Mq;)e[t++]=r&255|QC,r>>>=7;return e[t]=r|0,ZC.bytes=t-n+1,e}var Fq=m7,$q=128,JC=127;function m7(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw m7.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&JC)<<o:(i&JC)*Math.pow(2,o),o+=7}while(i>=$q);return m7.bytes=s-n,t}var Kq=Math.pow(2,7),Vq=Math.pow(2,14),Hq=Math.pow(2,21),qq=Math.pow(2,28),zq=Math.pow(2,35),Wq=Math.pow(2,42),Gq=Math.pow(2,49),jq=Math.pow(2,56),Yq=Math.pow(2,63),Xq=function(r){return r<Kq?1:r<Vq?2:r<Hq?3:r<qq?4:r<zq?5:r<Wq?6:r<Gq?7:r<jq?8:r<Yq?9:10},Qq={encode:Oq,decode:Fq,encodingLength:Xq},Jq=Qq,Sf=Jq;function Af(r,e=0){return[Sf.decode(r,e),Sf.decode.bytes]}function fl(r,e,t=0){return Sf.encode(r,e,t),e}function hl(r){return Sf.encodingLength(r)}function ml(r,e){let t=e.byteLength,n=hl(r),o=n+hl(t),s=new Uint8Array(o+t);return fl(r,s,0),fl(t,s,n),s.set(e,o),new pl(r,t,e,s)}function ek(r){let e=jo(r),[t,n]=Af(e),[o,s]=Af(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new pl(t,o,i,e)}function tk(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&qC(r.bytes,t.bytes)}}var pl=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var rk=0,Zq="identity",nk=jo;function ez(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 ml(rk,nk(r))}var tz={code:rk,name:Zq,encode:nk,digest:ez};var b7={};V(b7,{sha256:()=>nz,sha512:()=>oz});var rz=20;function w7({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new y7(r,e,t,n,o)}var y7=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??rz,this.maxDigestLength=s}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?ok(n,this.code,t?.truncate):n.then(o=>ok(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ok(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 ml(e,r)}function ik(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var nz=w7({name:"sha2-256",code:18,encode:ik("SHA-256")}),oz=w7({name:"sha2-512",code:19,encode:ik("SHA-512")});function ak(r,e){let{bytes:t,version:n}=r;return n===0?iz(t,x7(r),e??oo.encoder):az(t,x7(r),e??dl.encoder)}var ck=new WeakMap;function x7(r){let e=ck.get(r);if(e==null){let t=new Map;return ck.set(r,t),t}return e}var w2=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Tf)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==cz)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=ml(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&&tk(e.multihash,n.multihash)}toString(e){return ak(this,e)}toJSON(){return{"/":ak(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??lk(n,o,s.bytes))}else if(t[lz]===!0){let{version:n,multihash:o,code:s}=t,i=ek(o);return r.create(n,s,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!==Tf)throw new Error(`Version 0 CID must use dag-pb (code: ${Tf}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=lk(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Tf,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=jo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new pl(t.multihashCode,t.digestSize,s,o);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]=Af(e.subarray(t));return t+=f,d},o=n(),s=Tf;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=sz(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return x7(s).set(n,e),s}};function sz(r,e){switch(r[0]){case"Q":{let t=e??oo;return[oo.prefix,t.decode(`${oo.prefix}${r}`)]}case oo.prefix:{let t=e??oo;return[oo.prefix,t.decode(r)]}case dl.prefix:{let t=e??dl;return[dl.prefix,t.decode(r)]}case vf.prefix:{let t=e??vf;return[vf.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 iz(r,e,t){let{prefix:n}=t;if(n!==oo.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function az(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Tf=112,cz=18;function lk(r,e,t){let n=hl(r),o=n+hl(e),s=new Uint8Array(o+t.byteLength);return fl(r,s,0),fl(e,s,n),s.set(t,o),s}var lz=Symbol.for("@ipld/js-cid/CID");var E7={...p7,...a7,...h7,...s7,...i7,...l7,...u7,...d7,...f7,...c7},fbe={...b7,...g7};function uk(r=0){return new Uint8Array(r)}function fk(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var dk=fk("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),v7=fk("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=uk(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),uz={utf8:dk,"utf-8":dk,hex:E7.base16,latin1:v7,ascii:v7,binary:v7,...E7},hk=uz;function ha(r,e="utf8"){let t=hk[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var b2=class extends globalThis.Request{constructor(e,t={}){let n=t.method??"GET",o=so(t),s=t.body;x2(n,o)&&(t.method="UPGRADE"),super(e,t),Object.defineProperties(this,{body:{value:s,writable:!1},method:{value:n,writable:!1},headers:{value:o,writable:!1}})}};var pk={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var io=class extends globalThis.Response{constructor(e,t={}){let n=so(t),o=t.status??200;(o<200||o>599)&&(t.status=200),super(e,t),Object.defineProperties(this,{status:{value:o,writable:!1},statusText:{value:pk[o],writable:!1},headers:{value:n,writable:!1}})}};var dz=["dns","dns4","dns6","dnsaddr"];function kf(r,e){if(r instanceof URL)return r;let t=v2(r,e),{httpPath:n}=S2(r);return new URL(`http://${t}${n}`)}function _f(r){return r instanceof Uint8Array?r:r instanceof DataView?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r,0,r.byteLength)}function yk(r,e){let t={method:r.method,headers:r.headers};if((t.method!=="GET"||r.upgrade)&&t.method!=="HEAD"){let n=e;r.upgrade||(n=hz(e,r.headers.get("content-length"))),t.body=e7(n),t.duplex="half"}return new b2(S7(r).toString(),t)}async function wk(r,e){if(e.send(ha([`HTTP/1.1 ${r.status} ${r.statusText}`,...E2(r.headers),"",""].join(`\r
|
|
51
51
|
`))),r.body==null){await e.close().catch(n=>{e.abort(n)});return}let t=r.body.getReader();for(;;){let n=await t.read();if(n.value!=null&&(e.send(n.value)||await e.onDrain()),n.done)break}await e.close().catch(n=>{e.abort(n)})}var bk=ha(["HTTP/1.1 404 Not Found","Connection: close","",""].join(`\r
|
|
52
52
|
`)),fz=ha(["HTTP/1.1 400 Bad Request","Connection: close","",""].join(`\r
|
|
53
53
|
`)),Kbe=ha(["HTTP/1.1 500 Internal Server Error","Connection: close","",""].join(`\r
|
|
@@ -99,7 +99,7 @@ a=end-of-candidates
|
|
|
99
99
|
`:`
|
|
100
100
|
`;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
101
101
|
a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
102
|
-
a=ice-pwd:`+e+t)}catch{}return r}var Ww=O("libp2p-webrtc-noise:");function rL(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=O(n,"hex"),s=sr(He.code,o),i=Hw.decode(qw(e)),a=Ww.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Ke([Ww,i,s.bytes],a):Ke([Ww,s.bytes,i],a)}function Wj(r,e){return r.role==="server"}async function nL(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=zw(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=ZP(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=eL(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=zw(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Qo(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Wj(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(JP(d))}let s=QP(r.localDescription?.sdp);if(s==null)throw new Zs("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=rL(s,n.remoteAddr,n.role),a=Gm({prologueBytes:i})(n),c=th({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=rh({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),r.close(),s}}async function oL(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Js({peerConnection:s,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:s,muxerFactory:i}}var Mg=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[ts]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[xe]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Xe(o));let s=zP(),{peerConnection:i,muxerFactory:a}=await oL("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await nL(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new Lg("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(vu.exactMatch)}};function sL(r){return e=>new Mg(e,r)}function iL(r){return e=>new Bg(e,r)}var Gj=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 jj(r,e,t){let n,o=new Promise((s,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}=Gj(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=cr(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function aL(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=jj(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function cL(){throw new Error("WebSocket Servers can not be created in the browser!")}var Yj=1024*1024*4,Xj=10,Gw=class extends ls{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??Yj,this.checkBufferedAmountTask=oc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??Xj),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=O(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(ee(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function lL(r){return new Gw(r)}var jw=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[ts]=!0;[Symbol.toStringTag]="@libp2p/websockets";[xe]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=lL({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=ks(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new R("websockets:open-connection")),await aL(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new ba(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return cL({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>wo.exactMatch(t)||Ai.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function uL(r={}){return e=>new jw(e,r)}var dL={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function fL(r={}){let e;return r.name!=null&&r.version!=null&&(e=`${r.name}/${r.version} ${$0()}`),{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[uC(),iL(),sL(),uL()],connectionEncrypters:[Gm()],streamMuxers:[jT(),RP()],peerDiscovery:[ZT(dL)],services:{autoNAT:JT(),dcutr:hC(),delegatedContentRouting:lS(hd()),delegatedPeerRouting:uS(hd()),dht:kP({clientMode:!0}),identify:j_(),identifyPush:Y_(),ping:FP(),http:K_()}}}async function hL(r,e){let t=e??{};t.privateKey==null&&e.datastore!=null&&(t.privateKey=await y8(e.datastore,e.keychain));let n=fL({...t,name:t.nodeInfo?.name??r.info.name,version:t.nodeInfo?.version??r.info.version});return n.datastore=n.datastore??e.datastore,await AA({...n,...t})}async function Qj(r,e){return r8(e)?e:hL(r,{...e,dns:r.dns,logger:r.logger,datastore:r.datastore})}function pL(r,e){let t;Object.defineProperty(r,"libp2p",{configurable:!0,enumerable:!0,get(){if(t!=null)return t;throw new Cr}});let n={name:"libp2p",start:async o=>{t==null&&(t=await Qj(o,e));try{o.hasRouter("libp2p-router")||o.addRouter(IA(t)),r8(o.libp2p)&&await o.libp2p.start()}catch(s){if(s.name!=="NotStartedError")throw s}},stop:async()=>{await t?.stop()}};return r.addMixin(n),r}var Qw={};V(Qw,{code:()=>iY,decode:()=>cY,decodeOptions:()=>oY,encode:()=>aY,encodeOptions:()=>rY,name:()=>sY,toByteView:()=>gL});var mL=42;function gL(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Jj(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=K.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new B(b.tag,mL),new B(b.bytes,t)]}function Zj(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function eY(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function tY(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Yw={float64:!0,typeEncoders:{Map:tY,Object:Jj,undefined:Zj,number:eY}},rY={...Yw,typeEncoders:{...Yw.typeEncoders}};function nY(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return K.decode(e.subarray(1))}var Xw={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[mL]:nY}},oY={...Xw,tags:{...Xw.tags}},sY="dag-cbor",iY=113,aY=r=>ki(r,Yw),cY=r=>xn(gL(r),Xw);var rb={};V(rb,{code:()=>bY,decode:()=>bL,encode:()=>wL,format:()=>xY,name:()=>wY,parse:()=>vY,stringify:()=>xY});var Jw=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(b.equals(t.type,b.array)&&(t.elements++,t.elements!==1&&e.push([44])),b.equals(t.type,b.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[b.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[b.negint.major](e,t){this[b.uint.major](e,t)}[b.bytes.major](e,t){throw new Error(`${$n} unsupported type: Uint8Array`)}[b.string.major](e,t){this.prefix(e);let n=Ga(JSON.stringify(t.value));e.push(n.length>32?Ti(n):n)}[b.array.major](e,t){this.prefix(e),this.inRecursive.push({type:b.array,elements:0}),e.push([91])}[b.map.major](e,t){this.prefix(e),this.inRecursive.push({type:b.map,elements:0}),e.push([123])}[b.tag.major](e,t){}[b.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(b.equals(i.type,b.array))e.push([93]);else if(b.equals(i.type,b.map))e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${$n} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function lY(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${$n} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==b.string||n.type!==b.string)throw new Error(`${$n} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${$n} unexpected duplicate map keys, this is not supported`)}var uY={addBreakTokens:!0,mapSorter:lY};function Zw(r,e){return e=Object.assign({},uY,e),b1(r,new Jw,e)}var Dl=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${W} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${W} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new B(b.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${W} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${W} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new B(b.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new B(i>=0?b.uint:b.negint,i,this._pos-e):new B(i>=0?b.uint:b.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${W} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new B(b.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${W} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${W} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${W} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(i=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(s&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(i=d));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(d=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(i=d))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${W} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${W} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new B(b.string,nx(t),this._pos-e);default:if(s<32)throw new Error(`${W} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${W} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new B(b.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new B(b.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new B(b.null,null,4);case 102:return this.expect([102,97,108,115,101]),new B(b.false,!1,5);case 116:return this.expect([116,114,117,101]),new B(b.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${W} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new B(b.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new B(b.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new B(b.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new B(b.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${W} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${W} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function eb(r,e){return e=Object.assign({tokenizer:new Dl(r,e)},e),xn(r,e)}function fY(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function hY(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=K.asCID(r);if(!e)return null;let t=e.toString();return[new B(b.map,1/0,1),new B(b.string,"/",1),new B(b.string,t,t.length),new B(b.break,void 0,1)]}function Ug(r){let e=$e.encode(r).slice(1);return[new B(b.map,1/0,1),new B(b.string,"/",1),new B(b.map,1/0,1),new B(b.string,"bytes",5),new B(b.string,e,e.length),new B(b.break,void 0,1),new B(b.break,void 0,1)]}function Rn(r){return Ug(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function pY(r){return Ug(new Uint8Array(r))}function mY(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function gY(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var yY={typeEncoders:{Object:hY,Buffer:Ug,Uint8Array:Ug,Int8Array:Rn,Uint16Array:Rn,Int16Array:Rn,Uint32Array:Rn,Int32Array:Rn,Float32Array:Rn,Float64Array:Rn,Uint8ClampedArray:Rn,BigInt64Array:Rn,BigUint64Array:Rn,DataView:Rn,ArrayBuffer:pY,undefined:mY,number:gY}},tb=class extends Dl{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(b.equals(e.type,b.map)){let t=this._next();if(b.equals(t.type,b.string)&&t.value==="/"){let n=this._next();if(b.equals(n.type,b.string)){let o=this._next();if(!b.equals(o.type,b.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new B(b.tag,42,0)}if(b.equals(n.type,b.map)){let o=this._next();if(b.equals(o.type,b.string)&&o.value==="bytes"){let s=this._next();if(b.equals(s.type,b.string)){for(let a=0;a<2;a++){let c=this._next();if(!b.equals(c.type,b.break))throw new Error("Invalid encoded Bytes form")}let i=$e.decode(`m${s.value}`);return new B(b.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},yL={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>K.parse(r())}},wY="dag-json",bY=297,wL=r=>Zw(r,yY),bL=r=>{let e=fY(r),t=Object.assign(yL,{tokenizer:new tb(e,yL)});return eb(e,t)},xY=r=>EY.decode(wL(r));var EY=new TextDecoder,vY=r=>bL(SY.encode(r)),SY=new TextEncoder;var AL=ti(i8(),1);var gr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},nh=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};async function EL(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
|
|
102
|
+
a=ice-pwd:`+e+t)}catch{}return r}var Ww=O("libp2p-webrtc-noise:");function rL(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=O(n,"hex"),s=sr(He.code,o),i=Hw.decode(qw(e)),a=Ww.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Ke([Ww,i,s.bytes],a):Ke([Ww,s.bytes,i],a)}function Wj(r,e){return r.role==="server"}async function nL(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=zw(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=ZP(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=eL(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=zw(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Qo(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Wj(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(JP(d))}let s=QP(r.localDescription?.sdp);if(s==null)throw new Zs("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=rL(s,n.remoteAddr,n.role),a=G0({prologueBytes:i})(n),c=th({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=rh({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),r.close(),s}}async function oL(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Js({peerConnection:s,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:s,muxerFactory:i}}var Mg=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[ts]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[xe]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Xe(o));let s=zP(),{peerConnection:i,muxerFactory:a}=await oL("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await nL(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new Lg("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(vu.exactMatch)}};function sL(r){return e=>new Mg(e,r)}function iL(r){return e=>new Bg(e,r)}var Gj=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 jj(r,e,t){let n,o=new Promise((s,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}=Gj(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=cr(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function aL(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=jj(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function cL(){throw new Error("WebSocket Servers can not be created in the browser!")}var Yj=1024*1024*4,Xj=10,Gw=class extends ls{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??Yj,this.checkBufferedAmountTask=oc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??Xj),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=O(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(ee(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function lL(r){return new Gw(r)}var jw=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[ts]=!0;[Symbol.toStringTag]="@libp2p/websockets";[xe]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=lL({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=ks(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new R("websockets:open-connection")),await aL(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new ba(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return cL({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>wo.exactMatch(t)||Ai.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function uL(r={}){return e=>new jw(e,r)}var dL={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function fL(r={}){let e;return r.name!=null&&r.version!=null&&(e=`${r.name}/${r.version} ${$m()}`),{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[uC(),iL(),sL(),uL()],connectionEncrypters:[G0()],streamMuxers:[jT(),RP()],peerDiscovery:[ZT(dL)],services:{autoNAT:JT(),dcutr:hC(),delegatedContentRouting:lS(hd()),delegatedPeerRouting:uS(hd()),dht:kP({clientMode:!0}),identify:j_(),identifyPush:Y_(),ping:FP(),http:K_()}}}async function hL(r,e){let t=e??{};t.privateKey==null&&e.datastore!=null&&(t.privateKey=await y8(e.datastore,e.keychain));let n=fL({...t,name:t.nodeInfo?.name??r.info.name,version:t.nodeInfo?.version??r.info.version});return n.datastore=n.datastore??e.datastore,await AA({...n,...t})}async function Qj(r,e){return r8(e)?e:hL(r,{...e,dns:r.dns,logger:r.logger,datastore:r.datastore})}function pL(r,e){let t;Object.defineProperty(r,"libp2p",{configurable:!0,enumerable:!0,get(){if(t!=null)return t;throw new Cr}});let n={name:"libp2p",start:async o=>{t==null&&(t=await Qj(o,e));try{o.hasRouter("libp2p-router")||o.addRouter(IA(t)),r8(o.libp2p)&&await o.libp2p.start()}catch(s){if(s.name!=="NotStartedError")throw s}},stop:async()=>{await t?.stop()}};return r.addMixin(n),r}var Qw={};V(Qw,{code:()=>iY,decode:()=>cY,decodeOptions:()=>oY,encode:()=>aY,encodeOptions:()=>rY,name:()=>sY,toByteView:()=>gL});var mL=42;function gL(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Jj(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=K.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new B(b.tag,mL),new B(b.bytes,t)]}function Zj(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function eY(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function tY(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Yw={float64:!0,typeEncoders:{Map:tY,Object:Jj,undefined:Zj,number:eY}},rY={...Yw,typeEncoders:{...Yw.typeEncoders}};function nY(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return K.decode(e.subarray(1))}var Xw={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[mL]:nY}},oY={...Xw,tags:{...Xw.tags}},sY="dag-cbor",iY=113,aY=r=>ki(r,Yw),cY=r=>xn(gL(r),Xw);var rb={};V(rb,{code:()=>bY,decode:()=>bL,encode:()=>wL,format:()=>xY,name:()=>wY,parse:()=>vY,stringify:()=>xY});var Jw=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(b.equals(t.type,b.array)&&(t.elements++,t.elements!==1&&e.push([44])),b.equals(t.type,b.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[b.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[b.negint.major](e,t){this[b.uint.major](e,t)}[b.bytes.major](e,t){throw new Error(`${$n} unsupported type: Uint8Array`)}[b.string.major](e,t){this.prefix(e);let n=Ga(JSON.stringify(t.value));e.push(n.length>32?Ti(n):n)}[b.array.major](e,t){this.prefix(e),this.inRecursive.push({type:b.array,elements:0}),e.push([91])}[b.map.major](e,t){this.prefix(e),this.inRecursive.push({type:b.map,elements:0}),e.push([123])}[b.tag.major](e,t){}[b.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(b.equals(i.type,b.array))e.push([93]);else if(b.equals(i.type,b.map))e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${$n} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function lY(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${$n} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==b.string||n.type!==b.string)throw new Error(`${$n} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${$n} unexpected duplicate map keys, this is not supported`)}var uY={addBreakTokens:!0,mapSorter:lY};function Zw(r,e){return e=Object.assign({},uY,e),b1(r,new Jw,e)}var Dl=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${W} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${W} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new B(b.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${W} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${W} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new B(b.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new B(i>=0?b.uint:b.negint,i,this._pos-e):new B(i>=0?b.uint:b.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${W} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new B(b.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${W} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${W} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${W} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(i=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(s&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(i=d));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(d=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(i=d))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${W} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${W} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new B(b.string,nx(t),this._pos-e);default:if(s<32)throw new Error(`${W} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${W} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new B(b.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new B(b.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new B(b.null,null,4);case 102:return this.expect([102,97,108,115,101]),new B(b.false,!1,5);case 116:return this.expect([116,114,117,101]),new B(b.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${W} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new B(b.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new B(b.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new B(b.break,void 0,1);if(this.ch()!==44)throw new Error(`${W} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new B(b.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${W} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${W} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function eb(r,e){return e=Object.assign({tokenizer:new Dl(r,e)},e),xn(r,e)}function fY(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function hY(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=K.asCID(r);if(!e)return null;let t=e.toString();return[new B(b.map,1/0,1),new B(b.string,"/",1),new B(b.string,t,t.length),new B(b.break,void 0,1)]}function Ug(r){let e=$e.encode(r).slice(1);return[new B(b.map,1/0,1),new B(b.string,"/",1),new B(b.map,1/0,1),new B(b.string,"bytes",5),new B(b.string,e,e.length),new B(b.break,void 0,1),new B(b.break,void 0,1)]}function Rn(r){return Ug(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function pY(r){return Ug(new Uint8Array(r))}function mY(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function gY(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var yY={typeEncoders:{Object:hY,Buffer:Ug,Uint8Array:Ug,Int8Array:Rn,Uint16Array:Rn,Int16Array:Rn,Uint32Array:Rn,Int32Array:Rn,Float32Array:Rn,Float64Array:Rn,Uint8ClampedArray:Rn,BigInt64Array:Rn,BigUint64Array:Rn,DataView:Rn,ArrayBuffer:pY,undefined:mY,number:gY}},tb=class extends Dl{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(b.equals(e.type,b.map)){let t=this._next();if(b.equals(t.type,b.string)&&t.value==="/"){let n=this._next();if(b.equals(n.type,b.string)){let o=this._next();if(!b.equals(o.type,b.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new B(b.tag,42,0)}if(b.equals(n.type,b.map)){let o=this._next();if(b.equals(o.type,b.string)&&o.value==="bytes"){let s=this._next();if(b.equals(s.type,b.string)){for(let a=0;a<2;a++){let c=this._next();if(!b.equals(c.type,b.break))throw new Error("Invalid encoded Bytes form")}let i=$e.decode(`m${s.value}`);return new B(b.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},yL={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>K.parse(r())}},wY="dag-json",bY=297,wL=r=>Zw(r,yY),bL=r=>{let e=fY(r),t=Object.assign(yL,{tokenizer:new tb(e,yL)});return eb(e,t)},xY=r=>EY.decode(wL(r));var EY=new TextDecoder,vY=r=>bL(SY.encode(r)),SY=new TextEncoder;var AL=ti(i8(),1);var gr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},nh=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};async function EL(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
|
|
103
103
|
`,"");let n=$e.decode(`m${r}`),o=ln(n),s=o[0][1][0][1][0],i=xL(o[0][1][0][1][1]),a=xL(o[0][1][0][1][2]),c=o[0][1][0][1][4][1],l=o[0][1][0][1][4][2],u=await e.decrypt(s,c,l,{iterations:i,keyLength:a*8,hash:"SHA-512",algorithm:"AES-CBC",signal:t?.signal}),f=ln(u)[2],h=ar.encode({Type:0,Data:f});return iu().privateKeyFromProtobuf(h)}function xL(r){if(r.length===0)return 0;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return parseInt(e,16)}var AY="/pkcs8/",IL="/info/",IY=Symbol.for("@libp2p/service-capabilities"),oh={iterations:1e4,salt:O("you should override this value with a crypto secure random number"),hash:"SHA-512",algorithm:"AES-GCM"},Rl={iterations:32767,saltLength:16,ivLength:12,hash:"SHA-256",keyLength:128,algorithm:"AES-GCM"},nb=20,Fg={minKeyLength:112/8,minSaltLength:128/8,minIterations:1e3},vL={"SHA-256":128,"SHA-384":192,"SHA-512":256};function sh(r){return r==null||typeof r!="string"?!1:r===(0,AL.default)(r.trim())&&r.length>0}function Nl(r){return new Me(AY+r)}function $g(r){return new Me(IL+r)}async function TY(r,e){let t=r.toProtobuf(),n=await He.digest(t);return e?.signal?.throwIfAborted(),ge.encode(n.bytes).substring(1)}function CY(r){if(typeof r=="string")return O(r);if(r instanceof Uint8Array)return ee(r)}var Kg=class{components;self;cipher;salt;keychainDekOptions;privateKeyDekOptions;constructor(e,t={}){if(this.components=e,this.self=t.selfKey??"self",this.salt=CY(t.salt)??oh.salt,this.keychainDekOptions={iterations:t.iterations??oh.iterations,hash:t.hash??oh.hash,keyLength:vL[t.hash??oh.hash],algorithm:oh.algorithm},this.privateKeyDekOptions={iterations:Rl.iterations,hash:Rl.hash,saltLength:Rl.saltLength,ivLength:Rl.ivLength,keyLength:Rl.keyLength,algorithm:Rl.algorithm},t.password!=null&&t.password.length<nb)throw new Error("password must be least 20 characters");if(this.salt.byteLength!=null&&this.salt.byteLength<Fg.minSaltLength)throw new Error(`salt must be least ${Fg.minSaltLength} bytes`);if(t.iterations!=null&&t.iterations<Fg.minIterations)throw new Error(`iterations must be least ${Fg.minIterations}`);if(vL[this.keychainDekOptions.hash]==null)throw new gr("Unsupported hash");this.cipher=SL(t.password??"",this.salt,this.keychainDekOptions,this.privateKeyDekOptions)}[IY]=["@ipshipyard/keychain"];async generateKey(e,t){let o=await(await this.components.getCrypto(t?.type??"Ed25519",t)).generatePrivateKey(t);return this.importKey(e,o,t)}async importKey(e,t,n){if(!sh(e))throw new gr(`Invalid key name '${e}'`);if(t==null)throw new gr("Key is required");if(await this.components.datastore.has(Nl(e),n))throw new gr(`Key '${e}' already exists`);let s=this.components.datastore.batch();return await this._importKey(e,t,this.cipher,s,n),await s.commit(n),t}async _importKey(e,t,n,o,s){let i=t.toProtobuf(),a=await n.encrypt(i),c=Ke([a.salt,a.iv,a.cipherText],a.salt.byteLength+a.iv.byteLength+a.cipherText.byteLength),l=$e.encode(c),u={name:e,id:await TY(t,s)};o.put(Nl(e),O(l)),o.put($g(e),O(JSON.stringify(u)))}async exportKey(e,t){if(!sh(e))throw new gr(`Invalid key name '${e}'`);return this._exportKey(e,this.cipher,t)}async _exportKey(e,t,n){let o=await this.components.datastore.get(Nl(e),n),s=M(o),i;if(s.includes("BEGIN ENCRYPTED PRIVATE KEY"))return EL(s,t,n);try{let a=$e.decode(s),c=a.subarray(0,16),l=a.subarray(16,28),u=a.subarray(28),d=await t.decrypt(c,l,u,n),f=ar.decode(d);if(f.Type==null)throw new nh("Unknown key type");return i=await this.components.getCrypto(f.Type,n),await i.privateKeyFromProtobuf(d)}catch(a){throw a.name==="OperationError"?new nh(a.message):a}}async removeKey(e,t){if(!sh(e)||e===this.self)throw new gr(`Invalid key name '${e}'`);let n=this.components.datastore.batch();n.delete(Nl(e)),n.delete($g(e)),await n.commit(t)}async*listKeys(e){let t={prefix:IL};for await(let n of this.components.datastore.query(t,e))yield JSON.parse(M(n.value))}async renameKey(e,t,n){if(!sh(e)||e===this.self)throw new gr(`Invalid old key name '${e}'`);if(!sh(t)||t===this.self)throw new gr(`Invalid new key name '${t}'`);let o=Nl(e),s=Nl(t),i=$g(e),a=$g(t);if(await this.components.datastore.has(s,n))throw new gr(`Key '${t}' already exists`);let l=await this.components.datastore.get(o,n),u=await this.components.datastore.get(i,n),d=JSON.parse(M(u));d.name=t;let f=this.components.datastore.batch();f.put(s,l),f.put(a,O(JSON.stringify(d))),f.delete(o),f.delete(i),await f.commit(n)}async rotateKeychainPass(e,t){if(typeof e!="string")throw new gr(`Invalid new pass type '${typeof e}'`);if(e.length<nb)throw new gr(`Invalid pass length ${e.length}, must be at least ${nb}`);let n=this.cipher,o=this.cipher=SL(e,this.salt,this.keychainDekOptions,this.privateKeyDekOptions),s=this.components.datastore.batch();for await(let i of this.listKeys(t)){let a=await this._exportKey(i.name,n);await this._importKey(i.name,a,o,s,t)}await s.commit(t)}async loadPublicKeyFromProtobuf(e,t){let n=br.decode(e);if(n.Type==null)throw new gr("Protobuf was missing Type");return(await this.components.getCrypto(n.Type,t)).publicKeyFromProtobuf(e,t)}},kY={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function SL(r,e,t,n){let o;async function s(l,u,d,f){let h,p=O(l),y=await crypto.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);try{h=await crypto.subtle.deriveKey({name:"PBKDF2",salt:ee(u),iterations:f.iterations,hash:{name:f.hash}},y,{name:f.algorithm??"AES-GCM",length:f.keyLength},!0,d)}catch(g){if(l==="")h=await crypto.subtle.importKey("jwk",kY,{name:f.algorithm??"AES-GCM"},!0,d);else throw g}return h}async function i(){if(r==="")return r;let l=await s(r,e,["encrypt","decrypt"],t);return(await crypto.subtle.exportKey("jwk",l)).k??""}async function a(l,u){o==null&&(o=await i());let d=crypto.getRandomValues(new Uint8Array(n.saltLength)),f=crypto.getRandomValues(new Uint8Array(n.ivLength)),h=await s(o,d,["encrypt"],n),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:f},h,l);return u?.signal?.throwIfAborted(),{salt:d,iv:f,cipherText:new Uint8Array(p)}}async function c(l,u,d,f){o==null&&(o=await i());let h=await s(o,l,["decrypt"],{iterations:f?.iterations??n.iterations,keyLength:f?.keyLength??n.keyLength,hash:f?.hash??n.hash,algorithm:f?.algorithm??"AES-GCM"}),p=await crypto.subtle.decrypt({name:f?.algorithm??"AES-GCM",iv:ee(u)},h,ee(d));return f?.signal?.throwIfAborted(),new Uint8Array(p)}return{encrypt:a,decrypt:c}}function TL(r){return e=>new Kg(e,r)}je.formatters.z=r=>r==null?"undefined":ge.baseEncode(r);je.formatters.b=r=>r==null?"undefined":pt.baseEncode(r);je.formatters.k=r=>r==null?"undefined":or.baseEncode(r);je.formatters.m=r=>r==null?"undefined":$e.baseEncode(r);je.formatters.e=r=>r==null?"undefined":_L(r);function CL(r,e=""){let t=kL(r.message),n=kL(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
104
104
|
`).join(`
|
|
105
105
|
${e}`)}`:`${t}
|
|
@@ -110,7 +110,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
110
110
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function _Y(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function _L(r,e=""){if(_Y(r)){let t=CL(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
111
111
|
${e}${r.errors.map(n=>`${_L(n,`${e}`)}`).join(`
|
|
112
112
|
${e}`)}`):t+=`
|
|
113
|
-
${e}[Error list was empty]`,t.trim()}return CL(r,e)}function PY(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 PL(r){return{forComponent(e){return LL(e,r)}}}function LL(r,e){let t=PY(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=je(`${r}:trace`,e)),Object.assign(je(r,e),{error:je(`${r}:error`,e),trace:t,newScope:n=>LL(`${r}:${n}`,e)})}function kL(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Jo=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:o}of e)await this.put(n,o,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 LY(r){return typeof r?.then=="function"}var ih=class extends Jo{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=Lo(t);if(LY(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(pt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(pt.encode(e.multihash.bytes));if(n==null)throw new tn;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(pt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(pt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:K.createV1(po,Ee(pt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var DLe=rc("blockstore:core:tiered");var DL="SHARDING";var ZLe=new Me(DL);var hDe=rc("datastore:core:tiered");var Vg=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=wd({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await ht(this.child),this.started=!0}async stop(){await Ct(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{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 Nu("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 o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Nu("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(s,t),yield s}})(),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 ob=new Me("/version"),NL=1;async function OL(r){if(!await r.has(ob)){await r.put(ob,O(`${NL}`));return}let e=await r.get(ob),t=M(e);if(parseInt(t,10)!==NL)throw new L1("Invalid datastore version, a datastore migration may be required")}var ub={};V(ub,{code:()=>lb,createLink:()=>zL,createNode:()=>qL,decode:()=>zY,encode:()=>qY,name:()=>HY,prepare:()=>ab,validate:()=>cb});var RY=new TextDecoder;function sb(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Hg(r,e){let t;[t,e]=sb(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 BL(r,e){let t;return[t,e]=sb(r,e),[t&7,t>>3,e]}function NY(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=BL(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Hg(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Hg(r,n),e.Name=RY.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=sb(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function ML(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=BL(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Hg(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Hg(r,t),n.push(NY(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 s&&(i.Data=s),i.Links=n||[],i}var FL=new TextEncoder,UL=2**32,OY=2**31;function BY(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=ah(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=FL.encode(r.Name);t-=n.length,e.set(n,t),t=ah(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ah(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function $L(r){let e=UY(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ah(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=BY(r.Links[o],t.subarray(0,n));n-=s,n=ah(t,n,s)-1,t[n]=18}return t}function MY(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ol(t)}if(typeof r.Name=="string"){let t=FL.encode(r.Name).length;e+=1+t+Ol(t)}return typeof r.Tsize=="number"&&(e+=1+Ol(r.Tsize)),e}function UY(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ol(t)}if(r.Links)for(let t of r.Links){let n=MY(t);e+=1+n+Ol(n)}return e}function ah(r,e,t){e-=Ol(t);let n=e;for(;t>=OY;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ol(r){return r%2===0&&r++,Math.floor((FY(r)+6)/7)}function FY(r){let e=0;return r>=UL&&(r=Math.floor(r/UL),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+$Y[r]}var $Y=[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 KY=["Data","Links"],VY=["Hash","Name","Tsize"],ib=new TextEncoder;function VL(r,e){if(r===e)return 0;let t=r.Name?ib.encode(r.Name):[],n=e.Name?ib.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function KL(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function HL(r){if(typeof r.asCID=="object"){let t=K.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=K.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=K.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=K.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 ab(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=ib.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(HL),e.Links.sort(VL);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function cb(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!KL(r,KY))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(!KL(t,VY))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&&VL(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function qL(r,e=[]){return ab({Data:r,Links:e})}function zL(r,e,t){return HL({Hash:t,Name:r,Tsize:e})}function WL(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var HY="dag-pb",lb=112;function qY(r){cb(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),$L(e)}function zY(r){let e=WL(r),t=ML(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=K.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function GL(r=[],e){let t={[lb]:ub,[po]:fi};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);gs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new lu(`Could not load codec for ${n}`)}}function jL(r=[],e){let t={};return r=[F3(),K3(),iu(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);gs(s)?o=await s:o=s,t[o.type]=o,t[o.code]=o}if(o!=null)return o;throw new uu(`Could not load crypto for ${o}`)}}function YL(r=[],e){let t={[He.code]:He,[Ze.code]:Ze};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);gs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new cu(`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 qg=0,Bl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},zg=class extends Jo{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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 tn;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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()}};function WY(r){return r[Symbol.asyncIterator]!=null}function XL(r){return r?.then!=null}function GY(r,e){let t=0;if(WY(r))return(async function*(){for await(let c of r){let l=e(c,t++);XL(l)&&await l,yield c}})();let n=ic(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i?.then=="function")return(async function*(){await i,yield o;for(let c of n){let l=e(c,t++);XL(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var db=GY;var jY=128,Ml=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 zg(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??jY}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new R("blocks:put:duplicate",e)),e):(n.onProgress?.(new R("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new R("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Br(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new R("blocks:put-many:duplicate",s)),!i}),o=db(n,async({cid:s})=>{t.onProgress?.(new R("blocks:put-many:providers:notify",s)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new R("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new Ou("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new R("blocks:get:providers:get",e));let i=await QL(e,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new R("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new R("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new R("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new R("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(db(e,async n=>{let o=await this.child.has(n,t),s=t.offline===!0;if(!o){if(s)throw new Ou("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 R("blocks:get-many:providers:get",n));let a=await QL(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new R("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new R("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 R("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new R("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 R("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function QL(r,e,t,n){let o=XY(r,t),s=new AbortController,i=de([s.signal,n.signal]);s.signal;let a=[];for(let c of e)YY(c)&&a.push(c);if(a.length===0)throw new vo(`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 o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(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{s.abort(),i.clear()}}function YY(r){return typeof r.retrieve=="function"}var XY=(r,e)=>{if(e==null)throw new A(`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,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(gs(o)?n=await o:n=o,!te(n.digest,r.multihash.digest))throw new va("Hash of downloaded block did not match multihash from passed CID")}};var Wg=class extends Ml{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 o=de([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=de([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=de([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=de([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Gg=class extends Ml{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await ht(this.child,...this.blockBrokers),this.started=!0}async stop(){await Ct(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new vo("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new vo(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Wg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var ZL="/pin/",JL="/pinned-block/",fb=or;function jg(r){return r.version===0&&(r=r.toV1()),new Me(`${ZL}${r.toString(fb)}`)}var Yg=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=jg(e);if(await this.datastore.has(n))throw new P1("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new A("Depth must be greater than or equal to 0");let s=(t.walker??i6())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>te(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,ki(i),t)}async#e(e,t,n){let o=new Me(`${JL}${fb.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=xn(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,ki(s),n),n.onProgress?.(new R("helia:pin:add",e))}}async*rm(e,t={}){let n=jg(e),o=await this.datastore.get(n,t),s=xn(o);await this.datastore.delete(n,t);let i=(t.walker??i6())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:s.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>te(u,e.bytes)),!0),{...t,depth:s.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:ZL+(e.cid!=null?`${e.cid.toString(or)}`:"")},e)){let o=K.parse(t.toString().substring(5),or),s=xn(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Me(`${JL}${fb.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=jg(e),o=await this.datastore.get(n,t);return xn(o)}async setMetadata(e,t,n){let o=jg(e),s=await this.datastore.get(o,n),i=xn(s);i.metadata=t??{},await this.datastore.put(o,ki(i),n)}};var QY=5,Xg=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??QY,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 ht(...this.routers)}async stop(){await Ct(...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 os("No content routers available");let n=new mt({concurrency:this.providerLookupConcurrency}),o=0,s=[],i=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=ya(this.routers,"findProviders").map(async function*(l){let u=0;t?.onProgress?.(new R("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let d of l.findProviders(e,t))u++,t?.onProgress?.(new R("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:d})),yield d}catch(d){s.push(d)}finally{i.log("router %s found %d providers for %c",l,u,e),t?.onProgress?.(new R("helia:routing:find-providers:end",{routing:l.name,cid:e,found:u})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of lr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.queue.find(u=>u.options.peer.equals(l.id))!=null)continue;n.add(async()=>{try{let u=await this.findPeer(l.id,t);return u.multiaddrs.length===0?null:{...u,protocols:l.protocols,routing:l.routing}}catch(u){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,u),null}},{peer:l.id,signal:t.signal}).catch(u=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,u)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new os("No content routers available");await Promise.all(ya(this.routers,"provide").map(async n=>{t?.onProgress?.(new R("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new R("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ya(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new R("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new R("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ya(this.routers,"put").map(async o=>{n?.onProgress?.(new R("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new R("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(ya(this.routers,"get").map(async s=>{t?.onProgress?.(new R("helia:routing:get:start",{routing:s.name,key:e}));try{return await s.get(e,t)}catch(i){this.log("router %s failed with %e",s,i),n.push(i)}finally{t?.onProgress?.(new R("helia:routing:get:end",{routing:s.name,key:e}))}}))}catch{}if(o==null)throw new D1(n,`Failed to get value key ${M(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new os("No peer routers available");let n=this,o=lr(...ya(this.routers,"findPeer").map(s=>(async function*(){t?.onProgress?.(new R("helia:routing:find-peer:start",{routing:s.name,peerId:e}));try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}finally{t?.onProgress?.(new R("helia:routing:find-peer:end",{routing:s.name,peerId:e}))}})()));for await(let s of o)if(s!=null)return s;throw new Te("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new os("No peer routers available");for await(let n of lr(...ya(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new R("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new R("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function ya(r,e){return r.filter(t=>t[e]!=null)}var Qg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??PL(),this.log=this.logger.forComponent("helia"),this.getHasher=YL(e.hashers,e.loadHasher),this.getCodec=GL(e.codecs,e.loadCodec),this.getCrypto=jL(e.cryptos,e.loadCrypto),this.dns=e.dns??A0(),this.metrics=e.metrics,this.events=new le,this.status="stopped",this.mixins=[];let t={blockstore:e.blockstore??new ih,datastore:e.datastore??new ta,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}};this.keychain=t.keychain=TL()(t),this.routing=t.routing=new Xg(t,{routers:(e.routers??[]).flatMap(o=>(typeof o=="function"&&(o=o(t)),[o])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=t.blockBrokers=(e.blockBrokers??[]).map(o=>(typeof o=="function"&&(o=o(t)),o));let n=new Gg(t,e);this.pins=new Yg(t.datastore,n,this.getCodec),this.blockstore=new Vg(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=t.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new vo(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await OL(this.datastore),await ht(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 Ct(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,o=this.blockstore.unwrap();this.log("gc start"),await Er(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new R("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new R("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var eD="7.0.1",tD="helia";function JY(r={}){return aS(pL(_S(rD({...r,codecs:[Qw,rb,Sh,...r.codecs??[]],hashers:[k3,...r.hashers??[]]}))))}function rD(r={}){return new Qg({name:tD,version:eD,...r})}return cD(ZY);})();
|
|
113
|
+
${e}[Error list was empty]`,t.trim()}return CL(r,e)}function PY(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 PL(r){return{forComponent(e){return LL(e,r)}}}function LL(r,e){let t=PY(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=je(`${r}:trace`,e)),Object.assign(je(r,e),{error:je(`${r}:error`,e),trace:t,newScope:n=>LL(`${r}:${n}`,e)})}function kL(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Jo=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:o}of e)await this.put(n,o,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 LY(r){return typeof r?.then=="function"}var ih=class extends Jo{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=Lo(t);if(LY(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(pt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(pt.encode(e.multihash.bytes));if(n==null)throw new tn;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(pt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(pt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:K.createV1(po,Ee(pt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var DLe=rc("blockstore:core:tiered");var DL="SHARDING";var ZLe=new Me(DL);var hDe=rc("datastore:core:tiered");var Vg=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=wd({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await ht(this.child),this.started=!0}async stop(){await Ct(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{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 Nu("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 o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Nu("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(s,t),yield s}})(),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 ob=new Me("/version"),NL=1;async function OL(r){if(!await r.has(ob)){await r.put(ob,O(`${NL}`));return}let e=await r.get(ob),t=M(e);if(parseInt(t,10)!==NL)throw new L1("Invalid datastore version, a datastore migration may be required")}var ub={};V(ub,{code:()=>lb,createLink:()=>zL,createNode:()=>qL,decode:()=>zY,encode:()=>qY,name:()=>HY,prepare:()=>ab,validate:()=>cb});var RY=new TextDecoder;function sb(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Hg(r,e){let t;[t,e]=sb(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 BL(r,e){let t;return[t,e]=sb(r,e),[t&7,t>>3,e]}function NY(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=BL(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Hg(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Hg(r,n),e.Name=RY.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=sb(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function ML(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=BL(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Hg(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Hg(r,t),n.push(NY(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 s&&(i.Data=s),i.Links=n||[],i}var FL=new TextEncoder,UL=2**32,OY=2**31;function BY(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=ah(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=FL.encode(r.Name);t-=n.length,e.set(n,t),t=ah(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ah(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function $L(r){let e=UY(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ah(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=BY(r.Links[o],t.subarray(0,n));n-=s,n=ah(t,n,s)-1,t[n]=18}return t}function MY(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ol(t)}if(typeof r.Name=="string"){let t=FL.encode(r.Name).length;e+=1+t+Ol(t)}return typeof r.Tsize=="number"&&(e+=1+Ol(r.Tsize)),e}function UY(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ol(t)}if(r.Links)for(let t of r.Links){let n=MY(t);e+=1+n+Ol(n)}return e}function ah(r,e,t){e-=Ol(t);let n=e;for(;t>=OY;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ol(r){return r%2===0&&r++,Math.floor((FY(r)+6)/7)}function FY(r){let e=0;return r>=UL&&(r=Math.floor(r/UL),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+$Y[r]}var $Y=[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 KY=["Data","Links"],VY=["Hash","Name","Tsize"],ib=new TextEncoder;function VL(r,e){if(r===e)return 0;let t=r.Name?ib.encode(r.Name):[],n=e.Name?ib.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function KL(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function HL(r){if(typeof r.asCID=="object"){let t=K.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=K.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=K.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=K.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 ab(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=ib.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(HL),e.Links.sort(VL);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function cb(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!KL(r,KY))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(!KL(t,VY))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&&VL(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function qL(r,e=[]){return ab({Data:r,Links:e})}function zL(r,e,t){return HL({Hash:t,Name:r,Tsize:e})}function WL(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var HY="dag-pb",lb=112;function qY(r){cb(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),$L(e)}function zY(r){let e=WL(r),t=ML(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=K.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function GL(r=[],e){let t={[lb]:ub,[po]:fi};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);gs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new lu(`Could not load codec for ${n}`)}}function jL(r=[],e){let t={};return r=[F3(),K3(),iu(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);gs(s)?o=await s:o=s,t[o.type]=o,t[o.code]=o}if(o!=null)return o;throw new uu(`Could not load crypto for ${o}`)}}function YL(r=[],e){let t={[He.code]:He,[Ze.code]:Ze};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);gs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new cu(`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 qg=0,Bl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},zg=class extends Jo{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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 tn;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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===qg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bl(`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()}};function WY(r){return r[Symbol.asyncIterator]!=null}function XL(r){return r?.then!=null}function GY(r,e){let t=0;if(WY(r))return(async function*(){for await(let c of r){let l=e(c,t++);XL(l)&&await l,yield c}})();let n=ic(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i?.then=="function")return(async function*(){await i,yield o;for(let c of n){let l=e(c,t++);XL(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var db=GY;var jY=128,Ml=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 zg(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??jY}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new R("blocks:put:duplicate",e)),e):(n.onProgress?.(new R("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new R("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Br(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new R("blocks:put-many:duplicate",s)),!i}),o=db(n,async({cid:s})=>{t.onProgress?.(new R("blocks:put-many:providers:notify",s)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new R("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new Ou("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new R("blocks:get:providers:get",e));let i=await QL(e,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new R("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new R("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new R("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new R("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(db(e,async n=>{let o=await this.child.has(n,t),s=t.offline===!0;if(!o){if(s)throw new Ou("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 R("blocks:get-many:providers:get",n));let a=await QL(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new R("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new R("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 R("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new R("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 R("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function QL(r,e,t,n){let o=XY(r,t),s=new AbortController,i=de([s.signal,n.signal]);s.signal;let a=[];for(let c of e)YY(c)&&a.push(c);if(a.length===0)throw new vo(`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 o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(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{s.abort(),i.clear()}}function YY(r){return typeof r.retrieve=="function"}var XY=(r,e)=>{if(e==null)throw new A(`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,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(gs(o)?n=await o:n=o,!te(n.digest,r.multihash.digest))throw new va("Hash of downloaded block did not match multihash from passed CID")}};var Wg=class extends Ml{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 o=de([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=de([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=de([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=de([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Gg=class extends Ml{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await ht(this.child,...this.blockBrokers),this.started=!0}async stop(){await Ct(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new vo("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new vo(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Wg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var ZL="/pin/",JL="/pinned-block/",fb=or;function jg(r){return r.version===0&&(r=r.toV1()),new Me(`${ZL}${r.toString(fb)}`)}var Yg=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=jg(e);if(await this.datastore.has(n))throw new P1("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new A("Depth must be greater than or equal to 0");let s=(t.walker??i6())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>te(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,ki(i),t)}async#e(e,t,n){let o=new Me(`${JL}${fb.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=xn(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,ki(s),n),n.onProgress?.(new R("helia:pin:add",e))}}async*rm(e,t={}){let n=jg(e),o=await this.datastore.get(n,t),s=xn(o);await this.datastore.delete(n,t);let i=(t.walker??i6())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:s.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>te(u,e.bytes)),!0),{...t,depth:s.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:ZL+(e.cid!=null?`${e.cid.toString(or)}`:"")},e)){let o=K.parse(t.toString().substring(5),or),s=xn(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Me(`${JL}${fb.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=jg(e),o=await this.datastore.get(n,t);return xn(o)}async setMetadata(e,t,n){let o=jg(e),s=await this.datastore.get(o,n),i=xn(s);i.metadata=t??{},await this.datastore.put(o,ki(i),n)}};var QY=5,Xg=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??QY,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 ht(...this.routers)}async stop(){await Ct(...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 os("No content routers available");let n=new mt({concurrency:this.providerLookupConcurrency}),o=0,s=[],i=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=ya(this.routers,"findProviders").map(async function*(l){let u=0;t?.onProgress?.(new R("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let d of l.findProviders(e,t))u++,t?.onProgress?.(new R("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:d})),yield d}catch(d){s.push(d)}finally{i.log("router %s found %d providers for %c",l,u,e),t?.onProgress?.(new R("helia:routing:find-providers:end",{routing:l.name,cid:e,found:u})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of lr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.queue.find(u=>u.options.peer.equals(l.id))!=null)continue;n.add(async()=>{try{let u=await this.findPeer(l.id,t);return u.multiaddrs.length===0?null:{...u,protocols:l.protocols,routing:l.routing}}catch(u){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,u),null}},{peer:l.id,signal:t.signal}).catch(u=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,u)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new os("No content routers available");await Promise.all(ya(this.routers,"provide").map(async n=>{t?.onProgress?.(new R("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new R("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ya(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new R("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new R("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ya(this.routers,"put").map(async o=>{n?.onProgress?.(new R("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new R("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(ya(this.routers,"get").map(async s=>{t?.onProgress?.(new R("helia:routing:get:start",{routing:s.name,key:e}));try{return await s.get(e,t)}catch(i){this.log("router %s failed with %e",s,i),n.push(i)}finally{t?.onProgress?.(new R("helia:routing:get:end",{routing:s.name,key:e}))}}))}catch{}if(o==null)throw new D1(n,`Failed to get value key ${M(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new os("No peer routers available");let n=this,o=lr(...ya(this.routers,"findPeer").map(s=>(async function*(){t?.onProgress?.(new R("helia:routing:find-peer:start",{routing:s.name,peerId:e}));try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}finally{t?.onProgress?.(new R("helia:routing:find-peer:end",{routing:s.name,peerId:e}))}})()));for await(let s of o)if(s!=null)return s;throw new Te("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new os("No peer routers available");for await(let n of lr(...ya(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new R("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new R("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function ya(r,e){return r.filter(t=>t[e]!=null)}var Qg=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??PL(),this.log=this.logger.forComponent("helia"),this.getHasher=YL(e.hashers,e.loadHasher),this.getCodec=GL(e.codecs,e.loadCodec),this.getCrypto=jL(e.cryptos,e.loadCrypto),this.dns=e.dns??Am(),this.metrics=e.metrics,this.events=new le,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new ih,datastore:e.datastore??new ta,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=TL()(this.components),this.routing=this.components.routing=new Xg(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 Gg(this.components,e);this.pins=new Yg(this.components.datastore,t,this.getCodec),this.blockstore=new Vg(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 vo(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await OL(this.datastore),await ht(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 Ct(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,o=this.blockstore.unwrap();this.log("gc start"),await Er(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new R("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new R("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var eD="7.0.2",tD="helia";function JY(r={}){return aS(pL(_S(rD({...r,codecs:[Qw,rb,Sh,...r.codecs??[]],hashers:[k3,...r.hashers??[]]}))))}function rD(r={}){return new Qg({name:tD,version:eD,...r})}return cD(ZY);})();
|
|
114
114
|
/*! Bundled license information:
|
|
115
115
|
|
|
116
116
|
pvtsutils/build/index.js:
|