libp2p 1.5.2-a3e8beabd → 1.6.0-12106b5b0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,23 +1,23 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2P=(()=>{var $d=Object.create;var Ao=Object.defineProperty;var qd=Object.getOwnPropertyDescriptor;var Gd=Object.getOwnPropertyNames;var zd=Object.getPrototypeOf,Yd=Object.prototype.hasOwnProperty;var ht=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ee=(r,e)=>{for(var t in e)Ao(r,t,{get:e[t],enumerable:!0})},Ml=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gd(e))!Yd.call(r,o)&&o!==t&&Ao(r,o,{get:()=>e[o],enumerable:!(n=qd(e,o))||n.enumerable});return r};var Ht=(r,e,t)=>(t=r!=null?$d(zd(r)):{},Ml(e||!r||!r.__esModule?Ao(t,"default",{value:r,enumerable:!0}):t,r)),Wd=r=>Ml(Ao({},"__esModule",{value:!0}),r);var $u=ht(nn=>{"use strict";var Rg="[object ArrayBuffer]",Lt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Rg}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}},rc="string",_g=/^[0-9a-f]+$/i,Sg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ig=/^[a-zA-Z0-9-_]+$/,Yo=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=Lt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},tt=class{static toString(e,t=!1){let n=Lt.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}},Wo=class r{static isHex(e){return typeof e===rc&&_g.test(e)}static isBase64(e){return typeof e===rc&&Sg.test(e)}static isBase64Url(e){return typeof e===rc&&Ig.test(e)}static ToString(e,t="utf8"){let n=Lt.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 tt.toString(n,!0);case"utf16":case"utf16be":return tt.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 tt.fromString(e,!0);case"utf16":case"utf16be":return tt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Lt.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 Yo.fromString(e);case"utf16":case"utf16be":return tt.fromString(e);case"utf16le":case"usc2":return tt.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 Yo.toString(e);case"utf16":case"utf16be":return tt.toString(e);case"utf16le":case"usc2":return tt.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=Lt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Lt.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 tt.toString(e,t)}static FromUtf16String(e,t=!1){return tt.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,"")||""}};Wo.DEFAULT_UTF8_ENCODING="utf8";function Bg(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 Tg(...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 Cg(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}nn.BufferSourceConverter=Lt;nn.Convert=Wo;nn.assign=Bg;nn.combine=Tg;nn.isEqual=Cg});var Jf=ht((mv,Qf)=>{var ln=1e3,un=ln*60,fn=un*60,Ir=fn*24,l0=Ir*7,u0=Ir*365.25;Qf.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return f0(r);if(t==="number"&&isFinite(r))return e.long?d0(r):h0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function f0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*u0;case"weeks":case"week":case"w":return t*l0;case"days":case"day":case"d":return t*Ir;case"hours":case"hour":case"hrs":case"hr":case"h":return t*fn;case"minutes":case"minute":case"mins":case"min":case"m":return t*un;case"seconds":case"second":case"secs":case"sec":case"s":return t*ln;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function h0(r){var e=Math.abs(r);return e>=Ir?Math.round(r/Ir)+"d":e>=fn?Math.round(r/fn)+"h":e>=un?Math.round(r/un)+"m":e>=ln?Math.round(r/ln)+"s":r+"ms"}function d0(r){var e=Math.abs(r);return e>=Ir?Os(r,e,Ir,"day"):e>=fn?Os(r,e,fn,"hour"):e>=un?Os(r,e,un,"minute"):e>=ln?Os(r,e,ln,"second"):r+" ms"}function Os(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var th=ht((gv,eh)=>{function p0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Jf(),t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let h=0;h<f.length;h++)l=(l<<5)-l+f.charCodeAt(h),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,h=null,g,d;function p(...m){if(!p.enabled)return;let w=p,x=Number(new Date),b=x-(l||x);w.diff=b,w.prev=l,w.curr=x,l=x,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let A=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(S,C)=>{if(S==="%%")return"%";A++;let N=t.formatters[C];if(typeof N=="function"){let q=m[A];S=N.call(w,q),m.splice(A,1),A--}return S}),t.formatArgs.call(w,m),(w.log||t.log).apply(w,m)}return p.namespace=f,p.useColors=t.useColors(),p.color=t.selectColor(f),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==t.namespaces&&(g=t.namespaces,d=t.enabled(f)),d),set:m=>{h=m}}),typeof t.init=="function"&&t.init(p),p}function n(f,l){let h=t(this.namespace+(typeof l>"u"?":":l)+f);return h.log=this.log,h}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,h=(typeof f=="string"?f:"").split(/[\s,]+/),g=h.length;for(l=0;l<g;l++)h[l]&&(f=h[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.slice(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,h;for(l=0,h=t.skips.length;l<h;l++)if(t.skips[l].test(f))return!1;for(l=0,h=t.names.length;l<h;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack||f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}eh.exports=p0});var rh=ht((We,Us)=>{We.formatArgs=g0;We.save=y0;We.load=w0;We.useColors=m0;We.storage=b0();We.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();We.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function m0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function g0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Us.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}We.log=console.debug||console.log||(()=>{});function y0(r){try{r?We.storage.setItem("debug",r):We.storage.removeItem("debug")}catch{}}function w0(){let r;try{r=We.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function b0(){try{return localStorage}catch{}}Us.exports=th()(We);var{formatters:E0}=Us.exports;E0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Bh=ht((qA,Lc)=>{"use strict";var W0=Object.prototype.hasOwnProperty,$e="~";function co(){}Object.create&&(co.prototype=Object.create(null),new co().__proto__||($e=!1));function j0(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ih(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new j0(t,n||r,o),i=$e?$e+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 qs(r,e){--r._eventsCount===0?r._events=new co:delete r._events[e]}function Ue(){this._events=new co,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)W0.call(t,n)&&e.push($e?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ue.prototype.listeners=function(e){var t=$e?$e+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};Ue.prototype.listenerCount=function(e){var t=$e?$e+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ue.prototype.emit=function(e,t,n,o,s,i){var a=$e?$e+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var h=c.length,g;for(l=0;l<h;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(g=1,f=new Array(u-1);g<u;g++)f[g-1]=arguments[g];c[l].fn.apply(c[l].context,f)}}return!0};Ue.prototype.on=function(e,t,n){return Ih(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return Ih(this,e,t,n,!0)};Ue.prototype.removeListener=function(e,t,n,o){var s=$e?$e+e:e;if(!this._events[s])return this;if(!t)return qs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&qs(this,s);else{for(var a=0,c=[],u=i.length;a<u;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:qs(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=$e?$e+e:e,this._events[t]&&qs(this,t)):(this._events=new co,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=$e;Ue.EventEmitter=Ue;typeof Lc<"u"&&(Lc.exports=Ue)});var jc=ht((lR,Hh)=>{"use strict";function Kh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function hy(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return Kh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Kh(new o,t)}}Hh.exports=hy});var Yh=ht(ho=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,h;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,h=c&255,[u,f,l,h].join(".")},i=function(c){var u,f,l,h,g,d;for(u=[],l=h=0;h<=3&&c.length!==0;l=++h){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),g=d[0],f=d[1],c=c.substring(f),u.push(g)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,h,g;for(h=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),g=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)h=h*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")h=h*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")h=h*u+(10+t(c[l])-o)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");l++}if(l===g)throw new Error("empty octet");return[h,l]},r=function(){function c(u,f){var l,h,g,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(d=u.split("/",2),u=d[0],f=d[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(p){throw l=p,new Error("Invalid mask: "+f)}for(h=g=32;g>=0;h=--g)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(p){throw l=p,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,h;for(h=i(this.first),l=i(this.last),f=0;h<=l;)u(a(h),h,f),f++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),ho.ip2long=i,ho.long2ip=a,ho.Netmask=r}).call(ho)});var id=ht((y_,sd)=>{sd.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 fd=ht((P_,ud)=>{"use strict";ud.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var yd=ht((md,gd)=>{"use strict";var hi=fd(),{hasOwnProperty:dd}=Object.prototype,{propertyIsEnumerable:Py}=Object,Sn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Oy=md,hd={concatArrays:!1,ignoreUndefined:!1},di=r=>{let e=[];for(let t in r)dd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Py.call(r,n)&&e.push(n)}return e};function In(r){return Array.isArray(r)?Uy(r):hi(r)?My(r):r}function Uy(r){let e=r.slice(0,0);return di(r).forEach(t=>{Sn(e,t,In(r[t]))}),e}function My(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return di(r).forEach(t=>{Sn(e,t,In(r[t]))}),e}var pd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Sn(r,o,al(r[o],e[o],n)):Sn(r,o,In(e[o])))}),r),Fy=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)dd.call(s,a)&&(i.push(String(a)),s===r?Sn(n,o++,s[a]):Sn(n,o++,In(s[a])));n=pd(n,s,di(s).filter(a=>!i.includes(a)),t)}),n};function al(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Fy(r,e,t):!hi(e)||!hi(r)?In(e):pd(r,e,di(e),t)}gd.exports=function(...r){let e=al(In(hd),this!==Oy&&this||{},hd),t={_:{}};for(let n of r)if(n!==void 0){if(!hi(n))throw new TypeError("`"+n+"` is not an Option Object");t=al(t,{_:n},e)}return t._}});var uw={};Ee(uw,{createLibp2p:()=>lw});var Fl=Symbol.for("@libp2p/connection");var zi=Symbol.for("@libp2p/content-routing");var Yi=Symbol.for("@libp2p/peer-discovery");var Wi=Symbol.for("@libp2p/peer-id");function Ro(r){return r!=null&&!!r[Wi]}var ji=Symbol.for("@libp2p/peer-routing");var Vl="keep-alive";var ww=Symbol.for("@libp2p/transport");var $t;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})($t||($t={}));var qt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},y=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},_o=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var So="ERR_TIMEOUT";var ue=(r,...e)=>{try{[...e]}catch{}};var At=class extends EventTarget{#e=new Map;constructor(){super(),ue(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Zi(e,t))}},Xi=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Zi=globalThis.CustomEvent??Xi;function Kl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var ec={};Ee(ec,{Ed25519PrivateKey:()=>Rr,Ed25519PublicKey:()=>Kn,generateKeyPair:()=>xg,generateKeyPairFromSeed:()=>Hu,unmarshalEd25519PrivateKey:()=>bg,unmarshalEd25519PublicKey:()=>Eg});var ra={};Ee(ra,{base58btc:()=>ne,base58flickr:()=>ep});var _w=new Uint8Array(0);function Hl(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 Rt(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 $l(r){return new TextEncoder().encode(r)}function ql(r){return new TextDecoder().decode(r)}function jd(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),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var p=0,m=0,w=0,x=d.length;w!==x&&d[w]===0;)w++,p++;for(var b=(x-w)*f+1>>>0,A=new Uint8Array(b);w!==x;){for(var v=d[w],S=0,C=b-1;(v!==0||S<m)&&C!==-1;C--,S++)v+=256*A[C]>>>0,A[C]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=S,w++}for(var N=b-m;N!==b&&A[N]===0;)N++;for(var q=c.repeat(p);N<b;++N)q+=r.charAt(A[N]);return q}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var p=0;if(d[p]!==" "){for(var m=0,w=0;d[p]===c;)m++,p++;for(var x=(d.length-p)*u+1>>>0,b=new Uint8Array(x);d[p];){var A=t[d.charCodeAt(p)];if(A===255)return;for(var v=0,S=x-1;(A!==0||v<w)&&S!==-1;S--,v++)A+=a*b[S]>>>0,b[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=v,p++}if(d[p]!==" "){for(var C=x-w;C!==x&&b[C]===0;)C++;for(var N=new Uint8Array(m+(x-C)),q=m;C!==x;)N[q++]=b[C++];return N}}}function g(d){var p=h(d);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:h,decode:g}}var Xd=jd,Zd=Xd,zl=Zd;var Qi=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")}},Ji=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yl(this,e)}},ea=class{decoders;constructor(e){this.decoders=e}or(e){return Yl(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 Yl(r,e){return new ea({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ta=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 Qi(e,t,n),this.decoder=new Ji(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:r,prefix:e,encode:t,decode:n}){return new ta(r,e,t,n)}function Gt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=zl(t,r);return Fr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function Qd(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Jd(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;)s+="=";return s}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Fr({prefix:e,name:r,encode(o){return Jd(o,n,t)},decode(o){return Qd(o,n,t,r)}})}var ne=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ep=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var oa={};Ee(oa,{identity:()=>zt});var tp=Xl,Wl=128,rp=127,np=~rp,op=Math.pow(2,31);function Xl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=op;)e[t++]=r&255|Wl,r/=128;for(;r&np;)e[t++]=r&255|Wl,r>>>=7;return e[t]=r|0,Xl.bytes=t-n+1,e}var sp=na,ip=128,jl=127;function na(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw na.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&jl)<<o:(i&jl)*Math.pow(2,o),o+=7}while(i>=ip);return na.bytes=s-n,t}var ap=Math.pow(2,7),cp=Math.pow(2,14),lp=Math.pow(2,21),up=Math.pow(2,28),fp=Math.pow(2,35),hp=Math.pow(2,42),dp=Math.pow(2,49),pp=Math.pow(2,56),mp=Math.pow(2,63),gp=function(r){return r<ap?1:r<cp?2:r<lp?3:r<up?4:r<fp?5:r<hp?6:r<dp?7:r<pp?8:r<mp?9:10},yp={encode:tp,decode:sp,encodingLength:gp},wp=yp,kn=wp;function Dn(r,e=0){return[kn.decode(r,e),kn.decode.bytes]}function Vr(r,e,t=0){return kn.encode(r,e,t),e}function Kr(r){return kn.encodingLength(r)}function dt(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Vr(r,s,0),Vr(t,s,n),s.set(e,o),new Hr(r,t,e,s)}function gr(r){let e=Rt(r),[t,n]=Dn(e),[o,s]=Dn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Hr(t,o,i,e)}function Zl(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hl(r.bytes,t.bytes)}}var Hr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Ql=0,bp="identity",Jl=Rt;function Ep(r){return dt(Ql,Jl(r))}var zt={code:Ql,name:bp,encode:Jl,digest:Ep};var aa={};Ee(aa,{sha256:()=>Re,sha512:()=>xp});function ia({name:r,code:e,encode:t}){return new sa(r,e,t)}var sa=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?dt(this.code,t):t.then(n=>dt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function tu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=ia({name:"sha2-256",code:18,encode:tu("SHA-256")}),xp=ia({name:"sha2-512",code:19,encode:tu("SHA-512")});function ie(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r=0){return new Uint8Array(r)}function Le(r=0){return new Uint8Array(r)}function _e(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Le(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var ca={};Ee(ca,{base10:()=>vp});var vp=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var la={};Ee(la,{base16:()=>Ap,base16upper:()=>Rp});var Ap=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Rp=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ua={};Ee(ua,{base2:()=>_p});var _p=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fa={};Ee(fa,{base256emoji:()=>Cp});var ru=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}"),Sp=ru.reduce((r,e,t)=>(r[t]=e,r),[]),Ip=ru.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Bp(r){return r.reduce((e,t)=>(e+=Sp[t],e),"")}function Tp(r){let e=[];for(let t of r){let n=Ip[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Cp=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:Bp,decode:Tp});var ha={};Ee(ha,{base32:()=>Ge,base32hex:()=>Dp,base32hexpad:()=>Op,base32hexpadupper:()=>Up,base32hexupper:()=>Pp,base32pad:()=>Lp,base32padupper:()=>kp,base32upper:()=>Np,base32z:()=>Mp});var Ge=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Np=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Lp=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kp=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dp=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pp=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Op=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Up=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Mp=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var da={};Ee(da,{base36:()=>Fp,base36upper:()=>Vp});var Fp=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vp=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ma={};Ee(ma,{base64:()=>Pn,base64pad:()=>Kp,base64url:()=>pa,base64urlpad:()=>Hp});var Pn=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kp=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pa=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hp=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ga={};Ee(ga,{base8:()=>$p});var $p=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ya={};Ee(ya,{identity:()=>qp});var qp=Fr({prefix:"\0",name:"identity",encode:r=>ql(r),decode:r=>$l(r)});var Jw=new TextEncoder,eb=new TextDecoder;function nu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Wp(t,wa(r),e??ne.encoder);default:return jp(t,wa(r),e??Ge.encoder)}}var ou=new WeakMap;function wa(r){let e=ou.get(r);if(e==null){let t=new Map;return ou.set(r,t),t}return e}var nt=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!==On)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Xp)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=dt(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&&Zl(e.multihash,n.multihash)}toString(e){return nu(this,e)}toJSON(){return{"/":nu(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??su(n,o,s.bytes))}else if(t[Zp]===!0){let{version:n,multihash:o,code:s}=t,i=gr(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!==On)throw new Error(`Version 0 CID must use dag-pb (code: ${On}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=su(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,On,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=Rt(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 Hr(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[l,h]=Dn(e.subarray(t));return t+=h,l},o=n(),s=On;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(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=Yp(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 wa(s).set(n,e),s}};function Yp(r,e){switch(r[0]){case"Q":{let t=e??ne;return[ne.prefix,t.decode(`${ne.prefix}${r}`)]}case ne.prefix:{let t=e??ne;return[ne.prefix,t.decode(r)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Wp(r,e,t){let{prefix:n}=t;if(n!==ne.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 jp(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 On=112,Xp=18;function su(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Vr(r,s,0),Vr(e,s,n),s.set(t,o),s}var Zp=Symbol.for("@ipld/js-cid/CID");var Yt={...ya,...ua,...ga,...ca,...la,...ha,...da,...ra,...ma,...fa},gb={...aa,...oa};function au(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var iu=au("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ba=au("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=Le(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Qp={utf8:iu,"utf-8":iu,hex:Yt.base16,latin1:ba,ascii:ba,binary:ba,...Yt},Bo=Qp;function D(r,e="utf8"){let t=Bo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function et(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function $r(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Jp(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function qr(r,...e){if(!Jp(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function To(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$r(r.outputLen),$r(r.blockLen)}function Gr(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 cu(r,e){qr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Co=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Yr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ot=(r,e)=>r<<32-e|r>>>e;var Cb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var em=async()=>{};async function lu(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 Ea(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Wt(r){return typeof r=="string"&&(r=Ea(r)),qr(r),r}function No(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];qr(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}var zr=class{clone(){return this._cloneInto()}},tm={}.toString;function uu(r,e){if(e!==void 0&&tm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Lo(r){let e=n=>r().update(Wt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Wr(r=32){if(Co&&typeof Co.getRandomValues=="function")return Co.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function rm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var fu=(r,e,t)=>r&e^~r&t,hu=(r,e,t)=>r&e^r&t^e&t,jr=class extends zr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Yr(this.buffer)}update(e){Gr(this);let{view:t,buffer:n,blockLen:o}=this;e=Wt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Yr(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){Gr(this),cu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;rm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var ko=BigInt(4294967295),xa=BigInt(32);function du(r,e=!1){return e?{h:Number(r&ko),l:Number(r>>xa&ko)}:{h:Number(r>>xa&ko)|0,l:Number(r&ko)|0}}function nm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=du(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var om=(r,e)=>BigInt(r>>>0)<<xa|BigInt(e>>>0),sm=(r,e,t)=>r>>>t,im=(r,e,t)=>r<<32-t|e>>>t,am=(r,e,t)=>r>>>t|e<<32-t,cm=(r,e,t)=>r<<32-t|e>>>t,lm=(r,e,t)=>r<<64-t|e>>>t-32,um=(r,e,t)=>r>>>t-32|e<<64-t,fm=(r,e)=>e,hm=(r,e)=>r,dm=(r,e,t)=>r<<t|e>>>32-t,pm=(r,e,t)=>e<<t|r>>>32-t,mm=(r,e,t)=>e<<t-32|r>>>64-t,gm=(r,e,t)=>r<<t-32|e>>>64-t;function ym(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var wm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),bm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Em=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),xm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,vm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Am=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Rm={fromBig:du,split:nm,toBig:om,shrSH:sm,shrSL:im,rotrSH:am,rotrSL:cm,rotrBH:lm,rotrBL:um,rotr32H:fm,rotr32L:hm,rotlSH:dm,rotlSL:pm,rotlBH:mm,rotlBL:gm,add:ym,add3L:wm,add3H:bm,add4L:Em,add4H:xm,add5H:Am,add5L:vm},O=Rm;var[_m,Sm]=O.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),jt=new Uint32Array(80),Xt=new Uint32Array(80),va=class extends jr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:h,Gh:g,Gl:d,Hh:p,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,h,g,d,p,m]}set(e,t,n,o,s,i,a,c,u,f,l,h,g,d,p,m){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=u|0,this.El=f|0,this.Fh=l|0,this.Fl=h|0,this.Gh=g|0,this.Gl=d|0,this.Hh=p|0,this.Hl=m|0}process(e,t){for(let b=0;b<16;b++,t+=4)jt[b]=e.getUint32(t),Xt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let A=jt[b-15]|0,v=Xt[b-15]|0,S=O.rotrSH(A,v,1)^O.rotrSH(A,v,8)^O.shrSH(A,v,7),C=O.rotrSL(A,v,1)^O.rotrSL(A,v,8)^O.shrSL(A,v,7),N=jt[b-2]|0,q=Xt[b-2]|0,G=O.rotrSH(N,q,19)^O.rotrBH(N,q,61)^O.shrSH(N,q,6),U=O.rotrSL(N,q,19)^O.rotrBL(N,q,61)^O.shrSL(N,q,6),he=O.add4L(C,U,Xt[b-7],Xt[b-16]),le=O.add4H(he,S,G,jt[b-7],jt[b-16]);jt[b]=le|0,Xt[b]=he|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:h,Fh:g,Fl:d,Gh:p,Gl:m,Hh:w,Hl:x}=this;for(let b=0;b<80;b++){let A=O.rotrSH(l,h,14)^O.rotrSH(l,h,18)^O.rotrBH(l,h,41),v=O.rotrSL(l,h,14)^O.rotrSL(l,h,18)^O.rotrBL(l,h,41),S=l&g^~l&p,C=h&d^~h&m,N=O.add5L(x,v,C,Sm[b],Xt[b]),q=O.add5H(N,w,A,S,_m[b],jt[b]),G=N|0,U=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),he=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),le=n&s^n&a^s&a,Je=o&i^o&c^i&c;w=p|0,x=m|0,p=g|0,m=d|0,g=l|0,d=h|0,{h:l,l:h}=O.add(u|0,f|0,q|0,G|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let R=O.add3L(G,he,Je);n=O.add3H(R,q,U,le),o=R|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:h}=O.add(this.Eh|0,this.El|0,l|0,h|0),{h:g,l:d}=O.add(this.Fh|0,this.Fl|0,g|0,d|0),{h:p,l:m}=O.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:w,l:x}=O.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,s,i,a,c,u,f,l,h,g,d,p,m,w,x)}roundClean(){jt.fill(0),Xt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Xr=Lo(()=>new va);var Po={};Ee(Po,{abytes:()=>Zr,bitGet:()=>km,bitLen:()=>Lm,bitMask:()=>Un,bitSet:()=>Dm,bytesToHex:()=>It,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Qt,concatBytes:()=>Tt,createHmacDrbg:()=>_a,ensureBytes:()=>ae,equalBytes:()=>Cm,hexToBytes:()=>wr,hexToNumber:()=>Ra,isBytes:()=>Zt,numberToBytesBE:()=>Jt,numberToBytesLE:()=>br,numberToHexUnpadded:()=>yu,numberToVarBytesBE:()=>Tm,utf8ToBytes:()=>Nm,validateObject:()=>pt});var gu=BigInt(0),Do=BigInt(1),Im=BigInt(2);function Zt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Zr(r){if(!Zt(r))throw new Error("Uint8Array expected")}var Bm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function It(r){Zr(r);let e="";for(let t=0;t<r.length;t++)e+=Bm[r[t]];return e}function yu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ra(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var St={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function pu(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St._A&&r<=St._F)return r-(St._A-10);if(r>=St._a&&r<=St._f)return r-(St._a-10)}function wr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=pu(r.charCodeAt(s)),a=pu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return Ra(It(r))}function Qt(r){return Zr(r),Ra(It(Uint8Array.from(r).reverse()))}function Jt(r,e){return wr(r.toString(16).padStart(e*2,"0"))}function br(r,e){return Jt(r,e).reverse()}function Tm(r){return wr(yu(r))}function ae(r,e,t){let n;if(typeof e=="string")try{n=wr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(Zt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Tt(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Zr(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 Cm(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 Nm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Lm(r){let e;for(e=0;r>gu;r>>=Do,e+=1);return e}function km(r,e){return r>>BigInt(e)&Do}function Dm(r,e,t){return r|(t?Do:gu)<<BigInt(e)}var Un=r=>(Im<<BigInt(r-1))-Do,Aa=r=>new Uint8Array(r),mu=r=>Uint8Array.from(r);function _a(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Aa(r),o=Aa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Aa())=>{o=a(mu([0]),l),n=a(),l.length!==0&&(o=a(mu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,h=[];for(;l<e;){n=a();let g=n.slice();h.push(g),l+=n.length}return Tt(...h)};return(l,h)=>{i(),c(l);let g;for(;!(g=h(u()));)c();return i(),g}}var Pm={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Zt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function pt(r,e,t={}){let n=(o,s,i)=>{let a=Pm[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ye=BigInt(0),J=BigInt(1),Er=BigInt(2),Om=BigInt(3),Sa=BigInt(4),wu=BigInt(5),bu=BigInt(8),Um=BigInt(9),Mm=BigInt(16);function Z(r,e){let t=r%e;return t>=ye?t:e+t}function Fm(r,e,t){if(t<=ye||e<ye)throw new Error("Expected power/modulo > 0");if(t===J)return ye;let n=J;for(;e>ye;)e&J&&(n=n*r%t),r=r*r%t,e>>=J;return n}function ee(r,e,t){let n=r;for(;e-- >ye;)n*=n,n%=t;return n}function Oo(r,e){if(r===ye||e<=ye)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Z(r,e),n=e,o=ye,s=J,i=J,a=ye;for(;t!==ye;){let u=n/t,f=n%t,l=o-i*u,h=s-a*u;n=t,t=f,o=i,s=a,i=l,a=h}if(n!==J)throw new Error("invert: does not exist");return Z(o,e)}function Vm(r){let e=(r-J)/Er,t,n,o;for(t=r-J,n=0;t%Er===ye;t/=Er,n++);for(o=Er;o<r&&Fm(o,e,r)!==r-J;o++);if(n===1){let i=(r+J)/Sa;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+J)/Er;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),h=a.pow(c,t);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let g=1;for(let p=a.sqr(h);g<u&&!a.eql(p,a.ONE);g++)p=a.sqr(p);let d=a.pow(f,J<<BigInt(u-g-1));f=a.sqr(d),l=a.mul(l,d),h=a.mul(h,f),u=g}return l}}function Km(r){if(r%Sa===Om){let e=(r+J)/Sa;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%bu===wu){let e=(r-wu)/bu;return function(n,o){let s=n.mul(o,Er),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Er),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%Mm,Vm(r)}var Eu=(r,e)=>(Z(r,e)&J)===J,Hm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ia(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Hm.reduce((n,o)=>(n[o]="function",n),e);return pt(r,t)}function $m(r,e,t){if(t<ye)throw new Error("Expected power > 0");if(t===ye)return r.ONE;if(t===J)return e;let n=r.ONE,o=e;for(;t>ye;)t&J&&(n=r.mul(n,o)),o=r.sqr(o),t>>=J;return n}function qm(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Ba(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Uo(r,e,t=!1,n={}){if(r<=ye)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ba(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Km(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Un(o),ZERO:ye,ONE:J,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ye<=c&&c<r},is0:c=>c===ye,isOdd:c=>(c&J)===J,neg:c=>Z(-c,r),eql:(c,u)=>c===u,sqr:c=>Z(c*c,r),add:(c,u)=>Z(c+u,r),sub:(c,u)=>Z(c-u,r),mul:(c,u)=>Z(c*u,r),pow:(c,u)=>$m(a,c,u),div:(c,u)=>Z(c*Oo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Oo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>qm(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?br(c,s):Jt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Qt(c):Bt(c)}});return Object.freeze(a)}function xu(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function vu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Ta(r){let e=vu(r);return e+Math.ceil(e/2)}function Au(r,e,t=!1){let n=r.length,o=vu(e),s=Ta(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Qt(r),a=Z(i,e-J)+J;return t?br(a,o):Jt(a,o)}var zm=BigInt(0),Ca=BigInt(1);function Mo(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>zm;)s&Ca&&(i=i.add(a)),a=a.double(),s>>=Ca;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],u=o,f=u;for(let l=0;l<i;l++){f=u,c.push(f);for(let h=1;h<a;h++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),u=r.ZERO,f=r.BASE,l=BigInt(2**o-1),h=2**o,g=BigInt(o);for(let d=0;d<a;d++){let p=d*c,m=Number(i&l);i>>=g,m>c&&(m-=h,i+=Ca);let w=p,x=p+Math.abs(m)-1,b=d%2!==0,A=m<0;m===0?f=f.add(t(b,s[w])):u=u.add(t(A,s[x]))}return{p:u,f}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,u=s.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&s.set(o,a(u))),this.wNAF(c,u,i)}}}function Mn(r){return Ia(r.Fp),pt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ba(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var st=BigInt(0),ze=BigInt(1),Fo=BigInt(2),Ym=BigInt(8),Wm={zip215:!0};function jm(r){let e=Mn(r);return pt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Vo(r){let e=jm(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Fo<<BigInt(a*8)-ze,f=t.create,l=e.uvRatio||((_,E)=>{try{return{isValid:!0,value:t.sqrt(_*t.inv(E))}}catch{return{isValid:!1,value:st}}}),h=e.adjustScalarBytes||(_=>_),g=e.domain||((_,E,T)=>{if(E.length||T)throw new Error("Contexts/pre-hash are not supported");return _}),d=_=>typeof _=="bigint"&&st<_,p=(_,E)=>d(_)&&d(E)&&_<E,m=_=>_===st||p(_,u);function w(_,E){if(p(_,E))return _;throw new Error(`Expected valid scalar < ${E}, got ${typeof _} ${_}`)}function x(_){return _===st?_:w(_,n)}let b=new Map;function A(_){if(!(_ instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(E,T,k,P){if(this.ex=E,this.ey=T,this.ez=k,this.et=P,!m(E))throw new Error("x required");if(!m(T))throw new Error("y required");if(!m(k))throw new Error("z required");if(!m(P))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof v)throw new Error("extended point not allowed");let{x:T,y:k}=E||{};if(!m(T)||!m(k))throw new Error("invalid affine point");return new v(T,k,ze,f(T*k))}static normalizeZ(E){let T=t.invertBatch(E.map(k=>k.ez));return E.map((k,P)=>k.toAffine(T[P])).map(v.fromAffine)}_setWindowSize(E){this._WINDOW_SIZE=E,b.delete(this)}assertValidity(){let{a:E,d:T}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:k,ey:P,ez:F,et:V}=this,Y=f(k*k),$=f(P*P),z=f(F*F),de=f(z*z),oe=f(Y*E),ve=f(z*f(oe+$)),Ae=f(de+f(T*f(Y*$)));if(ve!==Ae)throw new Error("bad point: equation left != right (1)");let ge=f(k*P),Ne=f(F*V);if(ge!==Ne)throw new Error("bad point: equation left != right (2)")}equals(E){A(E);let{ex:T,ey:k,ez:P}=this,{ex:F,ey:V,ez:Y}=E,$=f(T*Y),z=f(F*P),de=f(k*Y),oe=f(V*P);return $===z&&de===oe}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:T,ey:k,ez:P}=this,F=f(T*T),V=f(k*k),Y=f(Fo*f(P*P)),$=f(E*F),z=T+k,de=f(f(z*z)-F-V),oe=$+V,ve=oe-Y,Ae=$-V,ge=f(de*ve),Ne=f(oe*Ae),vt=f(de*Ae),mr=f(ve*oe);return new v(ge,Ne,mr,vt)}add(E){A(E);let{a:T,d:k}=e,{ex:P,ey:F,ez:V,et:Y}=this,{ex:$,ey:z,ez:de,et:oe}=E;if(T===BigInt(-1)){let Nl=f((F-P)*(z+$)),Ll=f((F+P)*(z-$)),Gi=f(Ll-Nl);if(Gi===st)return this.double();let kl=f(V*Fo*oe),Dl=f(Y*Fo*de),Pl=Dl+kl,Ol=Ll+Nl,Ul=Dl-kl,Fd=f(Pl*Gi),Vd=f(Ol*Ul),Kd=f(Pl*Ul),Hd=f(Gi*Ol);return new v(Fd,Vd,Hd,Kd)}let ve=f(P*$),Ae=f(F*z),ge=f(Y*k*oe),Ne=f(V*de),vt=f((P+F)*($+z)-ve-Ae),mr=Ne-ge,Ln=Ne+ge,Cl=f(Ae-T*ve),Pd=f(vt*mr),Od=f(Ln*Cl),Ud=f(vt*Cl),Md=f(mr*Ln);return new v(Pd,Od,Md,Ud)}subtract(E){return this.add(E.negate())}wNAF(E){return N.wNAFCached(this,b,E,v.normalizeZ)}multiply(E){let{p:T,f:k}=this.wNAF(w(E,n));return v.normalizeZ([T,k])[0]}multiplyUnsafe(E){let T=x(E);return T===st?C:this.equals(C)||T===ze?this:this.equals(S)?this.wNAF(T).p:N.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(E){let{ex:T,ey:k,ez:P}=this,F=this.is0();E==null&&(E=F?Ym:t.inv(P));let V=f(T*E),Y=f(k*E),$=f(P*E);if(F)return{x:st,y:ze};if($!==ze)throw new Error("invZ was invalid");return{x:V,y:Y}}clearCofactor(){let{h:E}=e;return E===ze?this:this.multiplyUnsafe(E)}static fromHex(E,T=!1){let{d:k,a:P}=e,F=t.BYTES;E=ae("pointHex",E,F);let V=E.slice(),Y=E[F-1];V[F-1]=Y&-129;let $=Qt(V);$===st||(T?w($,u):w($,t.ORDER));let z=f($*$),de=f(z-ze),oe=f(k*z-P),{isValid:ve,value:Ae}=l(de,oe);if(!ve)throw new Error("Point.fromHex: invalid y coordinate");let ge=(Ae&ze)===ze,Ne=(Y&128)!==0;if(!T&&Ae===st&&Ne)throw new Error("Point.fromHex: x=0 and x_0=1");return Ne!==ge&&(Ae=f(-Ae)),v.fromAffine({x:Ae,y:$})}static fromPrivateKey(E){return U(E).point}toRawBytes(){let{x:E,y:T}=this.toAffine(),k=br(T,t.BYTES);return k[k.length-1]|=E&ze?128:0,k}toHex(){return It(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),v.ZERO=new v(st,ze,ze,st);let{BASE:S,ZERO:C}=v,N=Mo(v,a*8);function q(_){return Z(_,n)}function G(_){return q(Qt(_))}function U(_){let E=a;_=ae("private key",_,E);let T=ae("hashed private key",s(_),2*E),k=h(T.slice(0,E)),P=T.slice(E,2*E),F=G(k),V=S.multiply(F),Y=V.toRawBytes();return{head:k,prefix:P,scalar:F,point:V,pointBytes:Y}}function he(_){return U(_).pointBytes}function le(_=new Uint8Array,...E){let T=Tt(...E);return G(s(g(T,ae("context",_),!!o)))}function Je(_,E,T={}){_=ae("message",_),o&&(_=o(_));let{prefix:k,scalar:P,pointBytes:F}=U(E),V=le(T.context,k,_),Y=S.multiply(V).toRawBytes(),$=le(T.context,Y,F,_),z=q(V+$*P);x(z);let de=Tt(Y,br(z,t.BYTES));return ae("result",de,a*2)}let R=Wm;function L(_,E,T,k=R){let{context:P,zip215:F}=k,V=t.BYTES;_=ae("signature",_,2*V),E=ae("message",E),o&&(E=o(E));let Y=Qt(_.slice(V,2*V)),$,z,de;try{$=v.fromHex(T,F),z=v.fromHex(_.slice(0,V),F),de=S.multiplyUnsafe(Y)}catch{return!1}if(!F&&$.isSmallOrder())return!1;let oe=le(P,z.toRawBytes(),$.toRawBytes(),E);return z.add($.multiplyUnsafe(oe)).subtract(de).clearCofactor().equals(v.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:he,sign:Je,verify:L,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(_=8,E=v.BASE){return E._setWindowSize(_),E.multiply(BigInt(3)),E}}}}var La=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ru=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Qb=BigInt(0),Xm=BigInt(1),Na=BigInt(2),Zm=BigInt(5),_u=BigInt(10),Qm=BigInt(20),Jm=BigInt(40),Su=BigInt(80);function eg(r){let e=La,n=r*r%e*r%e,o=ee(n,Na,e)*n%e,s=ee(o,Xm,e)*r%e,i=ee(s,Zm,e)*s%e,a=ee(i,_u,e)*i%e,c=ee(a,Qm,e)*a%e,u=ee(c,Jm,e)*c%e,f=ee(u,Su,e)*u%e,l=ee(f,Su,e)*u%e,h=ee(l,_u,e)*i%e;return{pow_p_5_8:ee(h,Na,e)*r%e,b2:n}}function tg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function rg(r,e){let t=La,n=Z(e*e*e,t),o=Z(n*n*e,t),s=eg(r*o).pow_p_5_8,i=Z(r*n*s,t),a=Z(e*i*i,t),c=i,u=Z(i*Ru,t),f=a===r,l=a===Z(-r,t),h=a===Z(-r*Ru,t);return f&&(i=c),(l||h)&&(i=u),Eu(i,t)&&(i=Z(-i,t)),{isValid:f||l,value:i}}var Ct=Uo(La,void 0,!0),ka={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ct,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Xr,randomBytes:Wr,adjustScalarBytes:tg,uvRatio:rg},Qr=Vo(ka);function Iu(r,e,t){if(e.length>255)throw new Error("Context is too big");return No(Ea("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var Jb=Vo({...ka,domain:Iu}),eE=Vo({...ka,domain:Iu,prehash:Xr});var ng=(Ct.ORDER+BigInt(3))/BigInt(8),tE=Ct.pow(Na,ng),rE=Ct.sqrt(Ct.neg(Ct.ONE)),nE=(Ct.ORDER-BigInt(5))/BigInt(8),oE=BigInt(486662);var sE=xu(Ct,Ct.neg(BigInt(486664)));var iE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),aE=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),cE=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),lE=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var uE=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Jr=32,Nt=64,Ko=32;function Bu(){let r=Qr.utils.randomPrivateKey(),e=Qr.getPublicKey(r);return{privateKey:Lu(r,e),publicKey:e}}function Tu(r){if(r.length!==Ko)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=Qr.getPublicKey(e);return{privateKey:Lu(e,t),publicKey:t}}function Cu(r,e){let t=r.subarray(0,Ko);return Qr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Nu(r,e,t){return Qr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Lu(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Ko;n++)t[n]=r[n],t[Ko+n]=e[n];return t}var Me={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Da={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function ku(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=Me.get();t*=8;async function c(l,h){let g=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),p={name:e,iv:d};typeof h=="string"&&(h=D(h));let m;if(h.length===0){m=await a.subtle.importKey("jwk",Da,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",Da,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}let w=await a.subtle.encrypt(p,m,l);return _e([g,p.iv,new Uint8Array(w)])}async function u(l,h){let g=l.subarray(0,s),d=l.subarray(s,s+n),p=l.subarray(s+n),m={name:e,iv:d};typeof h=="string"&&(h=D(h));let w;if(h.length===0)try{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}catch{w=await a.subtle.importKey("jwk",Da,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}let x=await a.subtle.decrypt(m,w,p);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function en(r,e){let n=await ku().encrypt(r,e);return Pn.encode(n)}var ig=Math.pow(2,7),ag=Math.pow(2,14),cg=Math.pow(2,21),Pa=Math.pow(2,28),Oa=Math.pow(2,35),Ua=Math.pow(2,42),Ma=Math.pow(2,49),j=128,ke=127;function pe(r){if(r<ig)return 1;if(r<ag)return 2;if(r<cg)return 3;if(r<Pa)return 4;if(r<Oa)return 5;if(r<Ua)return 6;if(r<Ma)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fa(r,e,t=0){switch(pe(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lg(r,e,t=0){switch(pe(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Va(r,e){let t=r[e],n=0;if(n+=t&ke,t<j||(t=r[e+1],n+=(t&ke)<<7,t<j)||(t=r[e+2],n+=(t&ke)<<14,t<j)||(t=r[e+3],n+=(t&ke)<<21,t<j)||(t=r[e+4],n+=(t&ke)*Pa,t<j)||(t=r[e+5],n+=(t&ke)*Oa,t<j)||(t=r[e+6],n+=(t&ke)*Ua,t<j)||(t=r[e+7],n+=(t&ke)*Ma,t<j))return n;throw new RangeError("Could not decode varint")}function ug(r,e){let t=r.get(e),n=0;if(n+=t&ke,t<j||(t=r.get(e+1),n+=(t&ke)<<7,t<j)||(t=r.get(e+2),n+=(t&ke)<<14,t<j)||(t=r.get(e+3),n+=(t&ke)<<21,t<j)||(t=r.get(e+4),n+=(t&ke)*Pa,t<j)||(t=r.get(e+5),n+=(t&ke)*Oa,t<j)||(t=r.get(e+6),n+=(t&ke)*Ua,t<j)||(t=r.get(e+7),n+=(t&ke)*Ma,t<j))return n;throw new RangeError("Could not decode varint")}function De(r,e,t=0){return e==null&&(e=Le(pe(r))),e instanceof Uint8Array?Fa(r,e,t):lg(r,e,t)}function it(r,e=0){return r instanceof Uint8Array?Va(r,e):ug(r,e)}var Ka=new Float32Array([-0]),er=new Uint8Array(Ka.buffer);function Du(r,e,t){Ka[0]=r,e[t]=er[0],e[t+1]=er[1],e[t+2]=er[2],e[t+3]=er[3]}function Pu(r,e){return er[0]=r[e],er[1]=r[e+1],er[2]=r[e+2],er[3]=r[e+3],Ka[0]}var Ha=new Float64Array([-0]),Pe=new Uint8Array(Ha.buffer);function Ou(r,e,t){Ha[0]=r,e[t]=Pe[0],e[t+1]=Pe[1],e[t+2]=Pe[2],e[t+3]=Pe[3],e[t+4]=Pe[4],e[t+5]=Pe[5],e[t+6]=Pe[6],e[t+7]=Pe[7]}function Uu(r,e){return Pe[0]=r[e],Pe[1]=r[e+1],Pe[2]=r[e+2],Pe[3]=r[e+3],Pe[4]=r[e+4],Pe[5]=r[e+5],Pe[6]=r[e+6],Pe[7]=r[e+7],Ha[0]}var fg=BigInt(Number.MAX_SAFE_INTEGER),hg=BigInt(Number.MIN_SAFE_INTEGER),Ye=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 vr;if(e<fg&&e>hg)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>Mu&&(o=0n,++n>Mu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vr;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):vr}},vr=new Ye(0,0);vr.toBigInt=function(){return 0n};vr.zzEncode=vr.zzDecode=function(){return this};vr.length=function(){return 1};var Mu=4294967296n;function Fu(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 Vu(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 $a(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 at(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ho(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var qa=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,at(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 at(this,4);return Ho(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return Ho(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=Pu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=Uu(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 at(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Vu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw at(this,e);this.pos+=e}else do if(this.pos>=this.len)throw at(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ye(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 at(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 at(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 at(this,8);let e=Ho(this.buf,this.pos+=4),t=Ho(this.buf,this.pos+=4);return new Ye(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=Va(this.buf,this.pos);return this.pos+=pe(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 Ga(r){return new qa(r instanceof Uint8Array?r:r.subarray())}function Fe(r,e,t){let n=Ga(r);return e.decode(n,void 0,t)}function za(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Le(i);o+i>e&&(n=Le(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Ar=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ya(){}var ja=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},dg=za();function pg(r){return globalThis.Buffer!=null?Le(r):dg(r)}var Vn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ar(Ya,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ar(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Xa((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($o,10,Ye.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ye.fromBigInt(e);return this._push($o,t.length(),t)}uint64Number(e){return this._push(Fa,pe(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=Ye.fromBigInt(e).zzEncode();return this._push($o,t.length(),t)}sint64Number(e){let t=Ye.fromNumber(e).zzEncode();return this._push($o,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Wa,1,e?1:0)}fixed32(e){return this._push(Fn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ye.fromBigInt(e);return this._push(Fn,4,t.lo)._push(Fn,4,t.hi)}fixed64Number(e){let t=Ye.fromNumber(e);return this._push(Fn,4,t.lo)._push(Fn,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(Du,4,e)}double(e){return this._push(Ou,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Wa,1,0):this.uint32(t)._push(gg,t,e)}string(e){let t=Fu(e);return t!==0?this.uint32(t)._push($a,t,e):this._push(Wa,1,0)}fork(){return this.states=new ja(this),this.head=this.tail=new Ar(Ya,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 Ar(Ya,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=pg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Wa(r,e,t){e[t]=r&255}function mg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Xa=class extends Ar{next;constructor(e,t){super(mg,e,t),this.next=void 0}};function $o(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 Fn(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 gg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(yg,e,r),this},Vn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(wg,e,r),this});function yg(r,e,t){e.set(r,t)}function wg(r,e,t){r.length<40?$a(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function Za(){return new Vn}function Ve(r,e){let t=Za();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var tn;(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"})(tn||(tn={}));function qo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Qa(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return qo("enum",tn.VARINT,t,n)}function Ke(r,e){return qo("message",tn.LENGTH_DELIMITED,r,e)}var te;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(te||(te={}));var Ja;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Ja||(Ja={}));(function(r){r.codec=()=>Qa(Ja)})(te||(te={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),te.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=te.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(mt||(mt={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),te.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=te.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(gt||(gt={}));var Kn=class{_key;constructor(e){this._key=rn(e,Jr)}verify(e,t){return Nu(this._key,t,e)}marshal(){return this._key}get bytes(){return mt.encode({Type:te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},Rr=class{_key;_publicKey;constructor(e,t){this._key=rn(e,Nt),this._publicKey=rn(t,Jr)}sign(e){return Cu(this._key,e)}get public(){return new Kn(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=zt.digest(this.public.bytes);return ne.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return en(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function bg(r){if(r.length>Nt){r=rn(r,Nt+Jr);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Rr(n,o)}r=rn(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(Jr);return new Rr(e,t)}function Eg(r){return r=rn(r,Jr),new Kn(r)}async function xg(){let{privateKey:r,publicKey:e}=Bu();return new Rr(r,e)}async function Hu(r){let{privateKey:e,publicKey:t}=Tu(r);return new Rr(e,t)}function rn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new y(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function K(r,e="utf8"){let t=Bo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var uc={};Ee(uc,{MAX_RSA_KEY_SIZE:()=>Jn,RsaPrivateKey:()=>cn,RsaPublicKey:()=>Qn,fromJwk:()=>Wg,generateKeyPair:()=>jg,unmarshalRsaPrivateKey:()=>cc,unmarshalRsaPublicKey:()=>Yg});function yt(r){if(isNaN(r)||r<=0)throw new y("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Wr(r)}var or={};Ee(or,{exportToPem:()=>Hg,importFromPem:()=>$g,jwkToPkcs1:()=>Mg,jwkToPkix:()=>Vg,pkcs1ToJwk:()=>Ug,pkixToJwk:()=>Fg});var zo=class extends zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,To(e);let n=Wt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Gr(this),this.iHash.update(e),this}digestInto(e){Gr(this),qr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed: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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Hn=(r,e,t)=>new zo(r,e).update(t).digest();Hn.create=(r,e)=>new zo(r,e);function vg(r,e,t,n){To(r);let o=uu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if($r(s),$r(i),$r(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wt(e),u=Wt(t),f=new Uint8Array(i),l=Hn.create(r,c),h=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:h}}function Ag(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function tc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=vg(r,e,t,n),f,l=new Uint8Array(4),h=Yr(l),g=new Uint8Array(c.outputLen);for(let d=1,p=0;p<s;d++,p+=c.outputLen){let m=a.subarray(p,p+c.outputLen);h.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(g),m.set(g.subarray(0,m.length)),await lu(o-1,i,()=>{c._cloneInto(f).update(g).digestInto(g);for(let w=0;w<m.length;w++)m[w]^=g[w]})}return Ag(c,u,a,f,g)}var H=Ht($u());function _r(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 tr(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 u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function jo(...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 nc(){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=_r(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,_r(s,8)-n}function qu(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=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tr(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 Gu(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 qe(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 wx=Math.log(2);function Xo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function oc(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 Ot(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 qn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return oc(this.items)}},$n=[new Uint8Array([1])],zu="0123456789";var sn="",lt=new ArrayBuffer(0),sc=new Uint8Array(0),Gn="EndOfContent",Wu="OCTET STRING",ju="BIT STRING";function Ut(r){var e;return e=class extends r{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?H.BufferSourceConverter.toUint8Array(s.valueHex):sc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",lt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:H.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var kt=class{constructor({blockLength:e=0,error:t=sn,warnings:n=[],valueBeforeDecode:o=sc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=H.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:H.Convert.ToHex(this.valueBeforeDecodeView)}}};kt.NAME="baseBlock";var Oe=class extends kt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Oe.NAME="valueBlock";var Zo=class extends Ut(kt){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?H.BufferSourceConverter.toUint8Array(e.valueHex):sc,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",lt}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=tr(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=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let h=new Uint8Array(f);for(let g=0;g<u.length;g++)h[g]=u[g];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=u[h];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=_r(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Zo.NAME="identificationBlock";var Qo=class extends kt{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=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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=_r(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=tr(this.length,8);if(o.byteLength>127)return this.error="Too big length",lt;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}}};Qo.NAME="lengthBlock";var I={},Se=class extends kt{constructor({name:e=sn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Zo(o),this.lenBlock=new Qo(o),this.valueBlock=s?new s(o):new Oe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new qn;t||Xu(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?lt: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():H.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Gu(t,n)}};Se.NAME="BaseBlock";function Xu(r){if(r instanceof I.Constructed)for(let e of r.valueBlock.value)Xu(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Jo=class extends Se{constructor({value:e=sn,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Jo.NAME="BaseStringBlock";var es=class extends Ut(Oe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};es.NAME="PrimitiveValueBlock";var Zu,ts=class extends Se{constructor(e={}){super(e,es),this.idBlock.isConstructed=!1}};Zu=ts;I.Primitive=Zu;ts.NAME="PRIMITIVE";function Lg(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 Ds(r,e=0,t=r.length){let n=e,o=new Se({},Oe),s=new kt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Se;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=I.EndOfContent;break;case 1:c=I.Boolean;break;case 2:c=I.Integer;break;case 3:c=I.BitString;break;case 4:c=I.OctetString;break;case 5:c=I.Null;break;case 6:c=I.ObjectIdentifier;break;case 10:c=I.Enumerated;break;case 12:c=I.Utf8String;break;case 13:c=I.RelativeObjectIdentifier;break;case 14:c=I.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=I.Sequence;break;case 17:c=I.Set;break;case 18:c=I.NumericString;break;case 19:c=I.PrintableString;break;case 20:c=I.TeletexString;break;case 21:c=I.VideotexString;break;case 22:c=I.IA5String;break;case 23:c=I.UTCTime;break;case 24:c=I.GeneralizedTime;break;case 25:c=I.GraphicString;break;case 26:c=I.VisibleString;break;case 27:c=I.GeneralString;break;case 28:c=I.UniversalString;break;case 29:c=I.CharacterString;break;case 30:c=I.BmpString;break;case 31:c=I.DATE;break;case 32:c=I.TimeOfDay;break;case 33:c=I.DateTime;break;case 34:c=I.Duration;break;default:{let u=o.idBlock.isConstructed?new I.Constructed:new I.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?I.Constructed:I.Primitive}return o=Lg(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function an(r){if(!r.byteLength){let e=new Se({},Oe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ds(H.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function kg(r,e){return r?1:e}var wt=class extends Oe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=H.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;kg(this.isIndefiniteForm,n)>0;){let i=Ds(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Gn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new qn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?lt:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};wt.NAME="ConstructedValueBlock";var Qu,rr=class extends Se{constructor(e={}){super(e,wt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
2
+ "use strict";var Libp2P=(()=>{var $d=Object.create;var Ao=Object.defineProperty;var qd=Object.getOwnPropertyDescriptor;var Gd=Object.getOwnPropertyNames;var zd=Object.getPrototypeOf,Yd=Object.prototype.hasOwnProperty;var ht=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xe=(r,e)=>{for(var t in e)Ao(r,t,{get:e[t],enumerable:!0})},Vl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gd(e))!Yd.call(r,o)&&o!==t&&Ao(r,o,{get:()=>e[o],enumerable:!(n=qd(e,o))||n.enumerable});return r};var Ht=(r,e,t)=>(t=r!=null?$d(zd(r)):{},Vl(e||!r||!r.__esModule?Ao(t,"default",{value:r,enumerable:!0}):t,r)),Wd=r=>Vl(Ao({},"__esModule",{value:!0}),r);var Gu=ht(nn=>{"use strict";var Rg="[object ArrayBuffer]",Lt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Rg}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}},tc="string",_g=/^[0-9a-f]+$/i,Sg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ig=/^[a-zA-Z0-9-_]+$/,Yo=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=Lt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},et=class{static toString(e,t=!1){let n=Lt.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}},Wo=class r{static isHex(e){return typeof e===tc&&_g.test(e)}static isBase64(e){return typeof e===tc&&Sg.test(e)}static isBase64Url(e){return typeof e===tc&&Ig.test(e)}static ToString(e,t="utf8"){let n=Lt.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 et.toString(n,!0);case"utf16":case"utf16be":return et.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 et.fromString(e,!0);case"utf16":case"utf16be":return et.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Lt.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 Yo.fromString(e);case"utf16":case"utf16be":return et.fromString(e);case"utf16le":case"usc2":return et.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 Yo.toString(e);case"utf16":case"utf16be":return et.toString(e);case"utf16le":case"usc2":return et.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=Lt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Lt.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 et.toString(e,t)}static FromUtf16String(e,t=!1){return et.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,"")||""}};Wo.DEFAULT_UTF8_ENCODING="utf8";function Bg(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 Tg(...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 Cg(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}nn.BufferSourceConverter=Lt;nn.Convert=Wo;nn.assign=Bg;nn.combine=Tg;nn.isEqual=Cg});var th=ht((pv,eh)=>{var ln=1e3,un=ln*60,fn=un*60,Ir=fn*24,l0=Ir*7,u0=Ir*365.25;eh.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return f0(r);if(t==="number"&&isFinite(r))return e.long?d0(r):h0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function f0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*u0;case"weeks":case"week":case"w":return t*l0;case"days":case"day":case"d":return t*Ir;case"hours":case"hour":case"hrs":case"hr":case"h":return t*fn;case"minutes":case"minute":case"mins":case"min":case"m":return t*un;case"seconds":case"second":case"secs":case"sec":case"s":return t*ln;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function h0(r){var e=Math.abs(r);return e>=Ir?Math.round(r/Ir)+"d":e>=fn?Math.round(r/fn)+"h":e>=un?Math.round(r/un)+"m":e>=ln?Math.round(r/ln)+"s":r+"ms"}function d0(r){var e=Math.abs(r);return e>=Ir?Os(r,e,Ir,"day"):e>=fn?Os(r,e,fn,"hour"):e>=un?Os(r,e,un,"minute"):e>=ln?Os(r,e,ln,"second"):r+" ms"}function Os(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var nh=ht((mv,rh)=>{function p0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=th(),t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let h=0;h<f.length;h++)l=(l<<5)-l+f.charCodeAt(h),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,h=null,g,d;function p(...m){if(!p.enabled)return;let w=p,x=Number(new Date),b=x-(l||x);w.diff=b,w.prev=l,w.curr=x,l=x,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let A=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(S,C)=>{if(S==="%%")return"%";A++;let N=t.formatters[C];if(typeof N=="function"){let q=m[A];S=N.call(w,q),m.splice(A,1),A--}return S}),t.formatArgs.call(w,m),(w.log||t.log).apply(w,m)}return p.namespace=f,p.useColors=t.useColors(),p.color=t.selectColor(f),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==t.namespaces&&(g=t.namespaces,d=t.enabled(f)),d),set:m=>{h=m}}),typeof t.init=="function"&&t.init(p),p}function n(f,l){let h=t(this.namespace+(typeof l>"u"?":":l)+f);return h.log=this.log,h}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,h=(typeof f=="string"?f:"").split(/[\s,]+/),g=h.length;for(l=0;l<g;l++)h[l]&&(f=h[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.slice(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,h;for(l=0,h=t.skips.length;l<h;l++)if(t.skips[l].test(f))return!1;for(l=0,h=t.names.length;l<h;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack||f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}rh.exports=p0});var oh=ht((We,Us)=>{We.formatArgs=g0;We.save=y0;We.load=w0;We.useColors=m0;We.storage=b0();We.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();We.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function m0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function g0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Us.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}We.log=console.debug||console.log||(()=>{});function y0(r){try{r?We.storage.setItem("debug",r):We.storage.removeItem("debug")}catch{}}function w0(){let r;try{r=We.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function b0(){try{return localStorage}catch{}}Us.exports=nh()(We);var{formatters:E0}=Us.exports;E0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Bh=ht(($A,kc)=>{"use strict";var W0=Object.prototype.hasOwnProperty,$e="~";function co(){}Object.create&&(co.prototype=Object.create(null),new co().__proto__||($e=!1));function j0(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ih(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new j0(t,n||r,o),i=$e?$e+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 qs(r,e){--r._eventsCount===0?r._events=new co:delete r._events[e]}function Ue(){this._events=new co,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)W0.call(t,n)&&e.push($e?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ue.prototype.listeners=function(e){var t=$e?$e+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};Ue.prototype.listenerCount=function(e){var t=$e?$e+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ue.prototype.emit=function(e,t,n,o,s,i){var a=$e?$e+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var h=c.length,g;for(l=0;l<h;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(g=1,f=new Array(u-1);g<u;g++)f[g-1]=arguments[g];c[l].fn.apply(c[l].context,f)}}return!0};Ue.prototype.on=function(e,t,n){return Ih(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return Ih(this,e,t,n,!0)};Ue.prototype.removeListener=function(e,t,n,o){var s=$e?$e+e:e;if(!this._events[s])return this;if(!t)return qs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&qs(this,s);else{for(var a=0,c=[],u=i.length;a<u;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:qs(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=$e?$e+e:e,this._events[t]&&qs(this,t)):(this._events=new co,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=$e;Ue.EventEmitter=Ue;typeof kc<"u"&&(kc.exports=Ue)});var Xc=ht((cR,Hh)=>{"use strict";function Kh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function hy(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return Kh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Kh(new o,t)}}Hh.exports=hy});var Yh=ht(ho=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,h;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,h=c&255,[u,f,l,h].join(".")},i=function(c){var u,f,l,h,g,d;for(u=[],l=h=0;h<=3&&c.length!==0;l=++h){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),g=d[0],f=d[1],c=c.substring(f),u.push(g)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,h,g;for(h=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),g=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)h=h*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")h=h*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")h=h*u+(10+t(c[l])-o)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");l++}if(l===g)throw new Error("empty octet");return[h,l]},r=function(){function c(u,f){var l,h,g,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(d=u.split("/",2),u=d[0],f=d[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(p){throw l=p,new Error("Invalid mask: "+f)}for(h=g=32;g>=0;h=--g)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(p){throw l=p,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,h;for(h=i(this.first),l=i(this.last),f=0;h<=l;)u(a(h),h,f),f++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),ho.ip2long=i,ho.long2ip=a,ho.Netmask=r}).call(ho)});var id=ht((g_,sd)=>{sd.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 fd=ht((D_,ud)=>{"use strict";ud.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var yd=ht((md,gd)=>{"use strict";var fi=fd(),{hasOwnProperty:dd}=Object.prototype,{propertyIsEnumerable:Dy}=Object,Sn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Py=md,hd={concatArrays:!1,ignoreUndefined:!1},hi=r=>{let e=[];for(let t in r)dd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Dy.call(r,n)&&e.push(n)}return e};function In(r){return Array.isArray(r)?Oy(r):fi(r)?Uy(r):r}function Oy(r){let e=r.slice(0,0);return hi(r).forEach(t=>{Sn(e,t,In(r[t]))}),e}function Uy(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return hi(r).forEach(t=>{Sn(e,t,In(r[t]))}),e}var pd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Sn(r,o,ll(r[o],e[o],n)):Sn(r,o,In(e[o])))}),r),My=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)dd.call(s,a)&&(i.push(String(a)),s===r?Sn(n,o++,s[a]):Sn(n,o++,In(s[a])));n=pd(n,s,hi(s).filter(a=>!i.includes(a)),t)}),n};function ll(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?My(r,e,t):!fi(e)||!fi(r)?In(e):pd(r,e,hi(e),t)}gd.exports=function(...r){let e=ll(In(hd),this!==Py&&this||{},hd),t={_:{}};for(let n of r)if(n!==void 0){if(!fi(n))throw new TypeError("`"+n+"` is not an Option Object");t=ll(t,{_:n},e)}return t._}});var lw={};xe(lw,{createLibp2p:()=>cw});var Kl=Symbol.for("@libp2p/connection");var Gi=Symbol.for("@libp2p/content-routing");var zi=Symbol.for("@libp2p/peer-discovery");var Yi=Symbol.for("@libp2p/peer-id");function Ro(r){return r!=null&&!!r[Yi]}var Wi=Symbol.for("@libp2p/peer-routing");var Hl="keep-alive";var yw=Symbol.for("@libp2p/transport");var $t;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})($t||($t={}));var qt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},y=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},_o=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var So="ERR_TIMEOUT";var ue=(r,...e)=>{try{[...e]}catch{}};var At=class extends EventTarget{#e=new Map;constructor(){super(),ue(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Xi(e,t))}},ji=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Xi=globalThis.CustomEvent??ji;function $l(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Ja={};xe(Ja,{Ed25519PrivateKey:()=>Rr,Ed25519PublicKey:()=>Kn,generateKeyPair:()=>xg,generateKeyPairFromSeed:()=>qu,unmarshalEd25519PrivateKey:()=>bg,unmarshalEd25519PublicKey:()=>Eg});var ta={};xe(ta,{base58btc:()=>ne,base58flickr:()=>ep});var Rw=new Uint8Array(0);function ql(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 Rt(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 Gl(r){return new TextEncoder().encode(r)}function zl(r){return new TextDecoder().decode(r)}function jd(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),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var p=0,m=0,w=0,x=d.length;w!==x&&d[w]===0;)w++,p++;for(var b=(x-w)*f+1>>>0,A=new Uint8Array(b);w!==x;){for(var v=d[w],S=0,C=b-1;(v!==0||S<m)&&C!==-1;C--,S++)v+=256*A[C]>>>0,A[C]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=S,w++}for(var N=b-m;N!==b&&A[N]===0;)N++;for(var q=c.repeat(p);N<b;++N)q+=r.charAt(A[N]);return q}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var p=0;if(d[p]!==" "){for(var m=0,w=0;d[p]===c;)m++,p++;for(var x=(d.length-p)*u+1>>>0,b=new Uint8Array(x);d[p];){var A=t[d.charCodeAt(p)];if(A===255)return;for(var v=0,S=x-1;(A!==0||v<w)&&S!==-1;S--,v++)A+=a*b[S]>>>0,b[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=v,p++}if(d[p]!==" "){for(var C=x-w;C!==x&&b[C]===0;)C++;for(var N=new Uint8Array(m+(x-C)),q=m;C!==x;)N[q++]=b[C++];return N}}}function g(d){var p=h(d);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:h,decode:g}}var Xd=jd,Zd=Xd,Wl=Zd;var Zi=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")}},Qi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return jl(this,e)}},Ji=class{decoders;constructor(e){this.decoders=e}or(e){return jl(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 jl(r,e){return new Ji({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ea=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 Zi(e,t,n),this.decoder=new Qi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:r,prefix:e,encode:t,decode:n}){return new ea(r,e,t,n)}function Gt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Wl(t,r);return Fr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function Qd(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Jd(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;)s+="=";return s}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Fr({prefix:e,name:r,encode(o){return Jd(o,n,t)},decode(o){return Qd(o,n,t,r)}})}var ne=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ep=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var na={};xe(na,{identity:()=>zt});var tp=Ql,Xl=128,rp=127,np=~rp,op=Math.pow(2,31);function Ql(r,e,t){e=e||[],t=t||0;for(var n=t;r>=op;)e[t++]=r&255|Xl,r/=128;for(;r&np;)e[t++]=r&255|Xl,r>>>=7;return e[t]=r|0,Ql.bytes=t-n+1,e}var sp=ra,ip=128,Zl=127;function ra(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ra.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Zl)<<o:(i&Zl)*Math.pow(2,o),o+=7}while(i>=ip);return ra.bytes=s-n,t}var ap=Math.pow(2,7),cp=Math.pow(2,14),lp=Math.pow(2,21),up=Math.pow(2,28),fp=Math.pow(2,35),hp=Math.pow(2,42),dp=Math.pow(2,49),pp=Math.pow(2,56),mp=Math.pow(2,63),gp=function(r){return r<ap?1:r<cp?2:r<lp?3:r<up?4:r<fp?5:r<hp?6:r<dp?7:r<pp?8:r<mp?9:10},yp={encode:tp,decode:sp,encodingLength:gp},wp=yp,kn=wp;function Dn(r,e=0){return[kn.decode(r,e),kn.decode.bytes]}function Vr(r,e,t=0){return kn.encode(r,e,t),e}function Kr(r){return kn.encodingLength(r)}function dt(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Vr(r,s,0),Vr(t,s,n),s.set(e,o),new Hr(r,t,e,s)}function gr(r){let e=Rt(r),[t,n]=Dn(e),[o,s]=Dn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Hr(t,o,i,e)}function Jl(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ql(r.bytes,t.bytes)}}var Hr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var eu=0,bp="identity",tu=Rt;function Ep(r){return dt(eu,tu(r))}var zt={code:eu,name:bp,encode:tu,digest:Ep};var ia={};xe(ia,{sha256:()=>_e,sha512:()=>xp});function sa({name:r,code:e,encode:t}){return new oa(r,e,t)}var oa=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?dt(this.code,t):t.then(n=>dt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function nu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var _e=sa({name:"sha2-256",code:18,encode:nu("SHA-256")}),xp=sa({name:"sha2-512",code:19,encode:nu("SHA-512")});function ie(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r=0){return new Uint8Array(r)}function Le(r=0){return new Uint8Array(r)}function Se(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Le(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var aa={};xe(aa,{base10:()=>vp});var vp=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var ca={};xe(ca,{base16:()=>Ap,base16upper:()=>Rp});var Ap=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Rp=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var la={};xe(la,{base2:()=>_p});var _p=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ua={};xe(ua,{base256emoji:()=>Cp});var ou=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}"),Sp=ou.reduce((r,e,t)=>(r[t]=e,r),[]),Ip=ou.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Bp(r){return r.reduce((e,t)=>(e+=Sp[t],e),"")}function Tp(r){let e=[];for(let t of r){let n=Ip[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Cp=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:Bp,decode:Tp});var fa={};xe(fa,{base32:()=>Ge,base32hex:()=>Dp,base32hexpad:()=>Op,base32hexpadupper:()=>Up,base32hexupper:()=>Pp,base32pad:()=>Lp,base32padupper:()=>kp,base32upper:()=>Np,base32z:()=>Mp});var Ge=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Np=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Lp=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kp=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dp=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pp=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Op=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Up=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Mp=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ha={};xe(ha,{base36:()=>Fp,base36upper:()=>Vp});var Fp=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vp=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var pa={};xe(pa,{base64:()=>Pn,base64pad:()=>Kp,base64url:()=>da,base64urlpad:()=>Hp});var Pn=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kp=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),da=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hp=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ma={};xe(ma,{base8:()=>$p});var $p=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ga={};xe(ga,{identity:()=>qp});var qp=Fr({prefix:"\0",name:"identity",encode:r=>zl(r),decode:r=>Gl(r)});var Qw=new TextEncoder,Jw=new TextDecoder;function su(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Wp(t,ya(r),e??ne.encoder);default:return jp(t,ya(r),e??Ge.encoder)}}var iu=new WeakMap;function ya(r){let e=iu.get(r);if(e==null){let t=new Map;return iu.set(r,t),t}return e}var nt=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!==On)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Xp)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=dt(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&&Jl(e.multihash,n.multihash)}toString(e){return su(this,e)}toJSON(){return{"/":su(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??au(n,o,s.bytes))}else if(t[Zp]===!0){let{version:n,multihash:o,code:s}=t,i=gr(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!==On)throw new Error(`Version 0 CID must use dag-pb (code: ${On}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=au(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,On,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=Rt(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 Hr(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[l,h]=Dn(e.subarray(t));return t+=h,l},o=n(),s=On;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(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=Yp(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 ya(s).set(n,e),s}};function Yp(r,e){switch(r[0]){case"Q":{let t=e??ne;return[ne.prefix,t.decode(`${ne.prefix}${r}`)]}case ne.prefix:{let t=e??ne;return[ne.prefix,t.decode(r)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Wp(r,e,t){let{prefix:n}=t;if(n!==ne.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 jp(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 On=112,Xp=18;function au(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Vr(r,s,0),Vr(e,s,n),s.set(t,o),s}var Zp=Symbol.for("@ipld/js-cid/CID");var Yt={...ga,...la,...ma,...aa,...ca,...fa,...ha,...ta,...pa,...ua},mb={...ia,...na};function lu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var cu=lu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),wa=lu("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=Le(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Qp={utf8:cu,"utf-8":cu,hex:Yt.base16,latin1:wa,ascii:wa,binary:wa,...Yt},Bo=Qp;function D(r,e="utf8"){let t=Bo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Je(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function $r(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Jp(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function qr(r,...e){if(!Jp(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function To(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$r(r.outputLen),$r(r.blockLen)}function Gr(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 uu(r,e){qr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Co=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Yr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ot=(r,e)=>r<<32-e|r>>>e;var Tb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var em=async()=>{};async function fu(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 ba(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Wt(r){return typeof r=="string"&&(r=ba(r)),qr(r),r}function No(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];qr(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}var zr=class{clone(){return this._cloneInto()}},tm={}.toString;function hu(r,e){if(e!==void 0&&tm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Lo(r){let e=n=>r().update(Wt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Wr(r=32){if(Co&&typeof Co.getRandomValues=="function")return Co.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function rm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var du=(r,e,t)=>r&e^~r&t,pu=(r,e,t)=>r&e^r&t^e&t,jr=class extends zr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Yr(this.buffer)}update(e){Gr(this);let{view:t,buffer:n,blockLen:o}=this;e=Wt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Yr(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){Gr(this),uu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;rm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var ko=BigInt(4294967295),Ea=BigInt(32);function mu(r,e=!1){return e?{h:Number(r&ko),l:Number(r>>Ea&ko)}:{h:Number(r>>Ea&ko)|0,l:Number(r&ko)|0}}function nm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=mu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var om=(r,e)=>BigInt(r>>>0)<<Ea|BigInt(e>>>0),sm=(r,e,t)=>r>>>t,im=(r,e,t)=>r<<32-t|e>>>t,am=(r,e,t)=>r>>>t|e<<32-t,cm=(r,e,t)=>r<<32-t|e>>>t,lm=(r,e,t)=>r<<64-t|e>>>t-32,um=(r,e,t)=>r>>>t-32|e<<64-t,fm=(r,e)=>e,hm=(r,e)=>r,dm=(r,e,t)=>r<<t|e>>>32-t,pm=(r,e,t)=>e<<t|r>>>32-t,mm=(r,e,t)=>e<<t-32|r>>>64-t,gm=(r,e,t)=>r<<t-32|e>>>64-t;function ym(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var wm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),bm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Em=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),xm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,vm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Am=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Rm={fromBig:mu,split:nm,toBig:om,shrSH:sm,shrSL:im,rotrSH:am,rotrSL:cm,rotrBH:lm,rotrBL:um,rotr32H:fm,rotr32L:hm,rotlSH:dm,rotlSL:pm,rotlBH:mm,rotlBL:gm,add:ym,add3L:wm,add3H:bm,add4L:Em,add4H:xm,add5H:Am,add5L:vm},O=Rm;var[_m,Sm]=O.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),jt=new Uint32Array(80),Xt=new Uint32Array(80),xa=class extends jr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:h,Gh:g,Gl:d,Hh:p,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,h,g,d,p,m]}set(e,t,n,o,s,i,a,c,u,f,l,h,g,d,p,m){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=u|0,this.El=f|0,this.Fh=l|0,this.Fl=h|0,this.Gh=g|0,this.Gl=d|0,this.Hh=p|0,this.Hl=m|0}process(e,t){for(let b=0;b<16;b++,t+=4)jt[b]=e.getUint32(t),Xt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let A=jt[b-15]|0,v=Xt[b-15]|0,S=O.rotrSH(A,v,1)^O.rotrSH(A,v,8)^O.shrSH(A,v,7),C=O.rotrSL(A,v,1)^O.rotrSL(A,v,8)^O.shrSL(A,v,7),N=jt[b-2]|0,q=Xt[b-2]|0,G=O.rotrSH(N,q,19)^O.rotrBH(N,q,61)^O.shrSH(N,q,6),U=O.rotrSL(N,q,19)^O.rotrBL(N,q,61)^O.shrSL(N,q,6),he=O.add4L(C,U,Xt[b-7],Xt[b-16]),le=O.add4H(he,S,G,jt[b-7],jt[b-16]);jt[b]=le|0,Xt[b]=he|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:h,Fh:g,Fl:d,Gh:p,Gl:m,Hh:w,Hl:x}=this;for(let b=0;b<80;b++){let A=O.rotrSH(l,h,14)^O.rotrSH(l,h,18)^O.rotrBH(l,h,41),v=O.rotrSL(l,h,14)^O.rotrSL(l,h,18)^O.rotrBL(l,h,41),S=l&g^~l&p,C=h&d^~h&m,N=O.add5L(x,v,C,Sm[b],Xt[b]),q=O.add5H(N,w,A,S,_m[b],jt[b]),G=N|0,U=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),he=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),le=n&s^n&a^s&a,Qe=o&i^o&c^i&c;w=p|0,x=m|0,p=g|0,m=d|0,g=l|0,d=h|0,{h:l,l:h}=O.add(u|0,f|0,q|0,G|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let R=O.add3L(G,he,Qe);n=O.add3H(R,q,U,le),o=R|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:h}=O.add(this.Eh|0,this.El|0,l|0,h|0),{h:g,l:d}=O.add(this.Fh|0,this.Fl|0,g|0,d|0),{h:p,l:m}=O.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:w,l:x}=O.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,s,i,a,c,u,f,l,h,g,d,p,m,w,x)}roundClean(){jt.fill(0),Xt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Xr=Lo(()=>new xa);var Po={};xe(Po,{abytes:()=>Zr,bitGet:()=>km,bitLen:()=>Lm,bitMask:()=>Un,bitSet:()=>Dm,bytesToHex:()=>It,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Qt,concatBytes:()=>Tt,createHmacDrbg:()=>Ra,ensureBytes:()=>ae,equalBytes:()=>Cm,hexToBytes:()=>wr,hexToNumber:()=>Aa,isBytes:()=>Zt,numberToBytesBE:()=>Jt,numberToBytesLE:()=>br,numberToHexUnpadded:()=>bu,numberToVarBytesBE:()=>Tm,utf8ToBytes:()=>Nm,validateObject:()=>pt});var wu=BigInt(0),Do=BigInt(1),Im=BigInt(2);function Zt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Zr(r){if(!Zt(r))throw new Error("Uint8Array expected")}var Bm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function It(r){Zr(r);let e="";for(let t=0;t<r.length;t++)e+=Bm[r[t]];return e}function bu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Aa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var St={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function gu(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St._A&&r<=St._F)return r-(St._A-10);if(r>=St._a&&r<=St._f)return r-(St._a-10)}function wr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=gu(r.charCodeAt(s)),a=gu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return Aa(It(r))}function Qt(r){return Zr(r),Aa(It(Uint8Array.from(r).reverse()))}function Jt(r,e){return wr(r.toString(16).padStart(e*2,"0"))}function br(r,e){return Jt(r,e).reverse()}function Tm(r){return wr(bu(r))}function ae(r,e,t){let n;if(typeof e=="string")try{n=wr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(Zt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Tt(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Zr(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 Cm(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 Nm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Lm(r){let e;for(e=0;r>wu;r>>=Do,e+=1);return e}function km(r,e){return r>>BigInt(e)&Do}function Dm(r,e,t){return r|(t?Do:wu)<<BigInt(e)}var Un=r=>(Im<<BigInt(r-1))-Do,va=r=>new Uint8Array(r),yu=r=>Uint8Array.from(r);function Ra(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=va(r),o=va(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=va())=>{o=a(yu([0]),l),n=a(),l.length!==0&&(o=a(yu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,h=[];for(;l<e;){n=a();let g=n.slice();h.push(g),l+=n.length}return Tt(...h)};return(l,h)=>{i(),c(l);let g;for(;!(g=h(u()));)c();return i(),g}}var Pm={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Zt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function pt(r,e,t={}){let n=(o,s,i)=>{let a=Pm[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ye=BigInt(0),J=BigInt(1),Er=BigInt(2),Om=BigInt(3),_a=BigInt(4),Eu=BigInt(5),xu=BigInt(8),Um=BigInt(9),Mm=BigInt(16);function Z(r,e){let t=r%e;return t>=ye?t:e+t}function Fm(r,e,t){if(t<=ye||e<ye)throw new Error("Expected power/modulo > 0");if(t===J)return ye;let n=J;for(;e>ye;)e&J&&(n=n*r%t),r=r*r%t,e>>=J;return n}function ee(r,e,t){let n=r;for(;e-- >ye;)n*=n,n%=t;return n}function Oo(r,e){if(r===ye||e<=ye)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Z(r,e),n=e,o=ye,s=J,i=J,a=ye;for(;t!==ye;){let u=n/t,f=n%t,l=o-i*u,h=s-a*u;n=t,t=f,o=i,s=a,i=l,a=h}if(n!==J)throw new Error("invert: does not exist");return Z(o,e)}function Vm(r){let e=(r-J)/Er,t,n,o;for(t=r-J,n=0;t%Er===ye;t/=Er,n++);for(o=Er;o<r&&Fm(o,e,r)!==r-J;o++);if(n===1){let i=(r+J)/_a;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+J)/Er;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),h=a.pow(c,t);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let g=1;for(let p=a.sqr(h);g<u&&!a.eql(p,a.ONE);g++)p=a.sqr(p);let d=a.pow(f,J<<BigInt(u-g-1));f=a.sqr(d),l=a.mul(l,d),h=a.mul(h,f),u=g}return l}}function Km(r){if(r%_a===Om){let e=(r+J)/_a;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%xu===Eu){let e=(r-Eu)/xu;return function(n,o){let s=n.mul(o,Er),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Er),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%Mm,Vm(r)}var vu=(r,e)=>(Z(r,e)&J)===J,Hm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Sa(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Hm.reduce((n,o)=>(n[o]="function",n),e);return pt(r,t)}function $m(r,e,t){if(t<ye)throw new Error("Expected power > 0");if(t===ye)return r.ONE;if(t===J)return e;let n=r.ONE,o=e;for(;t>ye;)t&J&&(n=r.mul(n,o)),o=r.sqr(o),t>>=J;return n}function qm(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Ia(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Uo(r,e,t=!1,n={}){if(r<=ye)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ia(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Km(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Un(o),ZERO:ye,ONE:J,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ye<=c&&c<r},is0:c=>c===ye,isOdd:c=>(c&J)===J,neg:c=>Z(-c,r),eql:(c,u)=>c===u,sqr:c=>Z(c*c,r),add:(c,u)=>Z(c+u,r),sub:(c,u)=>Z(c-u,r),mul:(c,u)=>Z(c*u,r),pow:(c,u)=>$m(a,c,u),div:(c,u)=>Z(c*Oo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Oo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>qm(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?br(c,s):Jt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Qt(c):Bt(c)}});return Object.freeze(a)}function Au(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function Ru(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Ba(r){let e=Ru(r);return e+Math.ceil(e/2)}function _u(r,e,t=!1){let n=r.length,o=Ru(e),s=Ba(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Qt(r),a=Z(i,e-J)+J;return t?br(a,o):Jt(a,o)}var zm=BigInt(0),Ta=BigInt(1);function Mo(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>zm;)s&Ta&&(i=i.add(a)),a=a.double(),s>>=Ta;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],u=o,f=u;for(let l=0;l<i;l++){f=u,c.push(f);for(let h=1;h<a;h++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),u=r.ZERO,f=r.BASE,l=BigInt(2**o-1),h=2**o,g=BigInt(o);for(let d=0;d<a;d++){let p=d*c,m=Number(i&l);i>>=g,m>c&&(m-=h,i+=Ta);let w=p,x=p+Math.abs(m)-1,b=d%2!==0,A=m<0;m===0?f=f.add(t(b,s[w])):u=u.add(t(A,s[x]))}return{p:u,f}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,u=s.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&s.set(o,a(u))),this.wNAF(c,u,i)}}}function Mn(r){return Sa(r.Fp),pt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ia(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var st=BigInt(0),ze=BigInt(1),Fo=BigInt(2),Ym=BigInt(8),Wm={zip215:!0};function jm(r){let e=Mn(r);return pt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Vo(r){let e=jm(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Fo<<BigInt(a*8)-ze,f=t.create,l=e.uvRatio||((_,E)=>{try{return{isValid:!0,value:t.sqrt(_*t.inv(E))}}catch{return{isValid:!1,value:st}}}),h=e.adjustScalarBytes||(_=>_),g=e.domain||((_,E,T)=>{if(E.length||T)throw new Error("Contexts/pre-hash are not supported");return _}),d=_=>typeof _=="bigint"&&st<_,p=(_,E)=>d(_)&&d(E)&&_<E,m=_=>_===st||p(_,u);function w(_,E){if(p(_,E))return _;throw new Error(`Expected valid scalar < ${E}, got ${typeof _} ${_}`)}function x(_){return _===st?_:w(_,n)}let b=new Map;function A(_){if(!(_ instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(E,T,k,P){if(this.ex=E,this.ey=T,this.ez=k,this.et=P,!m(E))throw new Error("x required");if(!m(T))throw new Error("y required");if(!m(k))throw new Error("z required");if(!m(P))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof v)throw new Error("extended point not allowed");let{x:T,y:k}=E||{};if(!m(T)||!m(k))throw new Error("invalid affine point");return new v(T,k,ze,f(T*k))}static normalizeZ(E){let T=t.invertBatch(E.map(k=>k.ez));return E.map((k,P)=>k.toAffine(T[P])).map(v.fromAffine)}_setWindowSize(E){this._WINDOW_SIZE=E,b.delete(this)}assertValidity(){let{a:E,d:T}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:k,ey:P,ez:F,et:V}=this,Y=f(k*k),$=f(P*P),z=f(F*F),de=f(z*z),oe=f(Y*E),Ae=f(z*f(oe+$)),Re=f(de+f(T*f(Y*$)));if(Ae!==Re)throw new Error("bad point: equation left != right (1)");let ge=f(k*P),Ne=f(F*V);if(ge!==Ne)throw new Error("bad point: equation left != right (2)")}equals(E){A(E);let{ex:T,ey:k,ez:P}=this,{ex:F,ey:V,ez:Y}=E,$=f(T*Y),z=f(F*P),de=f(k*Y),oe=f(V*P);return $===z&&de===oe}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:T,ey:k,ez:P}=this,F=f(T*T),V=f(k*k),Y=f(Fo*f(P*P)),$=f(E*F),z=T+k,de=f(f(z*z)-F-V),oe=$+V,Ae=oe-Y,Re=$-V,ge=f(de*Ae),Ne=f(oe*Re),vt=f(de*Re),mr=f(Ae*oe);return new v(ge,Ne,mr,vt)}add(E){A(E);let{a:T,d:k}=e,{ex:P,ey:F,ez:V,et:Y}=this,{ex:$,ey:z,ez:de,et:oe}=E;if(T===BigInt(-1)){let kl=f((F-P)*(z+$)),Dl=f((F+P)*(z-$)),qi=f(Dl-kl);if(qi===st)return this.double();let Pl=f(V*Fo*oe),Ol=f(Y*Fo*de),Ul=Ol+Pl,Ml=Dl+kl,Fl=Ol-Pl,Fd=f(Ul*qi),Vd=f(Ml*Fl),Kd=f(Ul*Fl),Hd=f(qi*Ml);return new v(Fd,Vd,Hd,Kd)}let Ae=f(P*$),Re=f(F*z),ge=f(Y*k*oe),Ne=f(V*de),vt=f((P+F)*($+z)-Ae-Re),mr=Ne-ge,Ln=Ne+ge,Ll=f(Re-T*Ae),Pd=f(vt*mr),Od=f(Ln*Ll),Ud=f(vt*Ll),Md=f(mr*Ln);return new v(Pd,Od,Md,Ud)}subtract(E){return this.add(E.negate())}wNAF(E){return N.wNAFCached(this,b,E,v.normalizeZ)}multiply(E){let{p:T,f:k}=this.wNAF(w(E,n));return v.normalizeZ([T,k])[0]}multiplyUnsafe(E){let T=x(E);return T===st?C:this.equals(C)||T===ze?this:this.equals(S)?this.wNAF(T).p:N.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(E){let{ex:T,ey:k,ez:P}=this,F=this.is0();E==null&&(E=F?Ym:t.inv(P));let V=f(T*E),Y=f(k*E),$=f(P*E);if(F)return{x:st,y:ze};if($!==ze)throw new Error("invZ was invalid");return{x:V,y:Y}}clearCofactor(){let{h:E}=e;return E===ze?this:this.multiplyUnsafe(E)}static fromHex(E,T=!1){let{d:k,a:P}=e,F=t.BYTES;E=ae("pointHex",E,F);let V=E.slice(),Y=E[F-1];V[F-1]=Y&-129;let $=Qt(V);$===st||(T?w($,u):w($,t.ORDER));let z=f($*$),de=f(z-ze),oe=f(k*z-P),{isValid:Ae,value:Re}=l(de,oe);if(!Ae)throw new Error("Point.fromHex: invalid y coordinate");let ge=(Re&ze)===ze,Ne=(Y&128)!==0;if(!T&&Re===st&&Ne)throw new Error("Point.fromHex: x=0 and x_0=1");return Ne!==ge&&(Re=f(-Re)),v.fromAffine({x:Re,y:$})}static fromPrivateKey(E){return U(E).point}toRawBytes(){let{x:E,y:T}=this.toAffine(),k=br(T,t.BYTES);return k[k.length-1]|=E&ze?128:0,k}toHex(){return It(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),v.ZERO=new v(st,ze,ze,st);let{BASE:S,ZERO:C}=v,N=Mo(v,a*8);function q(_){return Z(_,n)}function G(_){return q(Qt(_))}function U(_){let E=a;_=ae("private key",_,E);let T=ae("hashed private key",s(_),2*E),k=h(T.slice(0,E)),P=T.slice(E,2*E),F=G(k),V=S.multiply(F),Y=V.toRawBytes();return{head:k,prefix:P,scalar:F,point:V,pointBytes:Y}}function he(_){return U(_).pointBytes}function le(_=new Uint8Array,...E){let T=Tt(...E);return G(s(g(T,ae("context",_),!!o)))}function Qe(_,E,T={}){_=ae("message",_),o&&(_=o(_));let{prefix:k,scalar:P,pointBytes:F}=U(E),V=le(T.context,k,_),Y=S.multiply(V).toRawBytes(),$=le(T.context,Y,F,_),z=q(V+$*P);x(z);let de=Tt(Y,br(z,t.BYTES));return ae("result",de,a*2)}let R=Wm;function L(_,E,T,k=R){let{context:P,zip215:F}=k,V=t.BYTES;_=ae("signature",_,2*V),E=ae("message",E),o&&(E=o(E));let Y=Qt(_.slice(V,2*V)),$,z,de;try{$=v.fromHex(T,F),z=v.fromHex(_.slice(0,V),F),de=S.multiplyUnsafe(Y)}catch{return!1}if(!F&&$.isSmallOrder())return!1;let oe=le(P,z.toRawBytes(),$.toRawBytes(),E);return z.add($.multiplyUnsafe(oe)).subtract(de).clearCofactor().equals(v.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:he,sign:Qe,verify:L,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(_=8,E=v.BASE){return E._setWindowSize(_),E.multiply(BigInt(3)),E}}}}var Na=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Su=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Zb=BigInt(0),Xm=BigInt(1),Ca=BigInt(2),Zm=BigInt(5),Iu=BigInt(10),Qm=BigInt(20),Jm=BigInt(40),Bu=BigInt(80);function eg(r){let e=Na,n=r*r%e*r%e,o=ee(n,Ca,e)*n%e,s=ee(o,Xm,e)*r%e,i=ee(s,Zm,e)*s%e,a=ee(i,Iu,e)*i%e,c=ee(a,Qm,e)*a%e,u=ee(c,Jm,e)*c%e,f=ee(u,Bu,e)*u%e,l=ee(f,Bu,e)*u%e,h=ee(l,Iu,e)*i%e;return{pow_p_5_8:ee(h,Ca,e)*r%e,b2:n}}function tg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function rg(r,e){let t=Na,n=Z(e*e*e,t),o=Z(n*n*e,t),s=eg(r*o).pow_p_5_8,i=Z(r*n*s,t),a=Z(e*i*i,t),c=i,u=Z(i*Su,t),f=a===r,l=a===Z(-r,t),h=a===Z(-r*Su,t);return f&&(i=c),(l||h)&&(i=u),vu(i,t)&&(i=Z(-i,t)),{isValid:f||l,value:i}}var Ct=Uo(Na,void 0,!0),La={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ct,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Xr,randomBytes:Wr,adjustScalarBytes:tg,uvRatio:rg},Qr=Vo(La);function Tu(r,e,t){if(e.length>255)throw new Error("Context is too big");return No(ba("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var Qb=Vo({...La,domain:Tu}),Jb=Vo({...La,domain:Tu,prehash:Xr});var ng=(Ct.ORDER+BigInt(3))/BigInt(8),eE=Ct.pow(Ca,ng),tE=Ct.sqrt(Ct.neg(Ct.ONE)),rE=(Ct.ORDER-BigInt(5))/BigInt(8),nE=BigInt(486662);var oE=Au(Ct,Ct.neg(BigInt(486664)));var sE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),iE=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),aE=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),cE=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var lE=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Jr=32,Nt=64,Ko=32;function Cu(){let r=Qr.utils.randomPrivateKey(),e=Qr.getPublicKey(r);return{privateKey:Du(r,e),publicKey:e}}function Nu(r){if(r.length!==Ko)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=Qr.getPublicKey(e);return{privateKey:Du(e,t),publicKey:t}}function Lu(r,e){let t=r.subarray(0,Ko);return Qr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function ku(r,e,t){return Qr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Du(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Ko;n++)t[n]=r[n],t[Ko+n]=e[n];return t}var Me={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var ka={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Pu(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=Me.get();t*=8;async function c(l,h){let g=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),p={name:e,iv:d};typeof h=="string"&&(h=D(h));let m;if(h.length===0){m=await a.subtle.importKey("jwk",ka,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",ka,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}let w=await a.subtle.encrypt(p,m,l);return Se([g,p.iv,new Uint8Array(w)])}async function u(l,h){let g=l.subarray(0,s),d=l.subarray(s,s+n),p=l.subarray(s+n),m={name:e,iv:d};typeof h=="string"&&(h=D(h));let w;if(h.length===0)try{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}catch{w=await a.subtle.importKey("jwk",ka,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}let x=await a.subtle.decrypt(m,w,p);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function en(r,e){let n=await Pu().encrypt(r,e);return Pn.encode(n)}var ig=Math.pow(2,7),ag=Math.pow(2,14),cg=Math.pow(2,21),Da=Math.pow(2,28),Pa=Math.pow(2,35),Oa=Math.pow(2,42),Ua=Math.pow(2,49),j=128,ke=127;function pe(r){if(r<ig)return 1;if(r<ag)return 2;if(r<cg)return 3;if(r<Da)return 4;if(r<Pa)return 5;if(r<Oa)return 6;if(r<Ua)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ma(r,e,t=0){switch(pe(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lg(r,e,t=0){switch(pe(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Fa(r,e){let t=r[e],n=0;if(n+=t&ke,t<j||(t=r[e+1],n+=(t&ke)<<7,t<j)||(t=r[e+2],n+=(t&ke)<<14,t<j)||(t=r[e+3],n+=(t&ke)<<21,t<j)||(t=r[e+4],n+=(t&ke)*Da,t<j)||(t=r[e+5],n+=(t&ke)*Pa,t<j)||(t=r[e+6],n+=(t&ke)*Oa,t<j)||(t=r[e+7],n+=(t&ke)*Ua,t<j))return n;throw new RangeError("Could not decode varint")}function ug(r,e){let t=r.get(e),n=0;if(n+=t&ke,t<j||(t=r.get(e+1),n+=(t&ke)<<7,t<j)||(t=r.get(e+2),n+=(t&ke)<<14,t<j)||(t=r.get(e+3),n+=(t&ke)<<21,t<j)||(t=r.get(e+4),n+=(t&ke)*Da,t<j)||(t=r.get(e+5),n+=(t&ke)*Pa,t<j)||(t=r.get(e+6),n+=(t&ke)*Oa,t<j)||(t=r.get(e+7),n+=(t&ke)*Ua,t<j))return n;throw new RangeError("Could not decode varint")}function De(r,e,t=0){return e==null&&(e=Le(pe(r))),e instanceof Uint8Array?Ma(r,e,t):lg(r,e,t)}function it(r,e=0){return r instanceof Uint8Array?Fa(r,e):ug(r,e)}var Va=new Float32Array([-0]),er=new Uint8Array(Va.buffer);function Ou(r,e,t){Va[0]=r,e[t]=er[0],e[t+1]=er[1],e[t+2]=er[2],e[t+3]=er[3]}function Uu(r,e){return er[0]=r[e],er[1]=r[e+1],er[2]=r[e+2],er[3]=r[e+3],Va[0]}var Ka=new Float64Array([-0]),Pe=new Uint8Array(Ka.buffer);function Mu(r,e,t){Ka[0]=r,e[t]=Pe[0],e[t+1]=Pe[1],e[t+2]=Pe[2],e[t+3]=Pe[3],e[t+4]=Pe[4],e[t+5]=Pe[5],e[t+6]=Pe[6],e[t+7]=Pe[7]}function Fu(r,e){return Pe[0]=r[e],Pe[1]=r[e+1],Pe[2]=r[e+2],Pe[3]=r[e+3],Pe[4]=r[e+4],Pe[5]=r[e+5],Pe[6]=r[e+6],Pe[7]=r[e+7],Ka[0]}var fg=BigInt(Number.MAX_SAFE_INTEGER),hg=BigInt(Number.MIN_SAFE_INTEGER),Ye=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 vr;if(e<fg&&e>hg)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>Vu&&(o=0n,++n>Vu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vr;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):vr}},vr=new Ye(0,0);vr.toBigInt=function(){return 0n};vr.zzEncode=vr.zzDecode=function(){return this};vr.length=function(){return 1};var Vu=4294967296n;function Ku(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 Hu(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 Ha(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 at(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ho(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var $a=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,at(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 at(this,4);return Ho(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return Ho(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=Uu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=Fu(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 at(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw at(this,e);this.pos+=e}else do if(this.pos>=this.len)throw at(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ye(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 at(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 at(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 at(this,8);let e=Ho(this.buf,this.pos+=4),t=Ho(this.buf,this.pos+=4);return new Ye(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=Fa(this.buf,this.pos);return this.pos+=pe(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 qa(r){return new $a(r instanceof Uint8Array?r:r.subarray())}function Fe(r,e,t){let n=qa(r);return e.decode(n,void 0,t)}function Ga(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Le(i);o+i>e&&(n=Le(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Ar=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function za(){}var Wa=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},dg=Ga();function pg(r){return globalThis.Buffer!=null?Le(r):dg(r)}var Vn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ar(za,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ar(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ja((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($o,10,Ye.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ye.fromBigInt(e);return this._push($o,t.length(),t)}uint64Number(e){return this._push(Ma,pe(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=Ye.fromBigInt(e).zzEncode();return this._push($o,t.length(),t)}sint64Number(e){let t=Ye.fromNumber(e).zzEncode();return this._push($o,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ya,1,e?1:0)}fixed32(e){return this._push(Fn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ye.fromBigInt(e);return this._push(Fn,4,t.lo)._push(Fn,4,t.hi)}fixed64Number(e){let t=Ye.fromNumber(e);return this._push(Fn,4,t.lo)._push(Fn,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(Ou,4,e)}double(e){return this._push(Mu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ya,1,0):this.uint32(t)._push(gg,t,e)}string(e){let t=Ku(e);return t!==0?this.uint32(t)._push(Ha,t,e):this._push(Ya,1,0)}fork(){return this.states=new Wa(this),this.head=this.tail=new Ar(za,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 Ar(za,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=pg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ya(r,e,t){e[t]=r&255}function mg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ja=class extends Ar{next;constructor(e,t){super(mg,e,t),this.next=void 0}};function $o(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 Fn(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 gg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(yg,e,r),this},Vn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(wg,e,r),this});function yg(r,e,t){e.set(r,t)}function wg(r,e,t){r.length<40?Ha(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function Xa(){return new Vn}function Ve(r,e){let t=Xa();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var tn;(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"})(tn||(tn={}));function qo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Za(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return qo("enum",tn.VARINT,t,n)}function Ke(r,e){return qo("message",tn.LENGTH_DELIMITED,r,e)}var te;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(te||(te={}));var Qa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Qa||(Qa={}));(function(r){r.codec=()=>Za(Qa)})(te||(te={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),te.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=te.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(mt||(mt={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),te.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=te.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(gt||(gt={}));var Kn=class{_key;constructor(e){this._key=rn(e,Jr)}verify(e,t){return ku(this._key,t,e)}marshal(){return this._key}get bytes(){return mt.encode({Type:te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=_e.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},Rr=class{_key;_publicKey;constructor(e,t){this._key=rn(e,Nt),this._publicKey=rn(t,Jr)}sign(e){return Lu(this._key,e)}get public(){return new Kn(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=_e.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=zt.digest(this.public.bytes);return ne.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return en(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function bg(r){if(r.length>Nt){r=rn(r,Nt+Jr);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Rr(n,o)}r=rn(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(Jr);return new Rr(e,t)}function Eg(r){return r=rn(r,Jr),new Kn(r)}async function xg(){let{privateKey:r,publicKey:e}=Cu();return new Rr(r,e)}async function qu(r){let{privateKey:e,publicKey:t}=Nu(r);return new Rr(e,t)}function rn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new y(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function K(r,e="utf8"){let t=Bo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var lc={};xe(lc,{MAX_RSA_KEY_SIZE:()=>Jn,RsaPrivateKey:()=>cn,RsaPublicKey:()=>Qn,fromJwk:()=>Wg,generateKeyPair:()=>jg,unmarshalRsaPrivateKey:()=>ac,unmarshalRsaPublicKey:()=>Yg});function yt(r){if(isNaN(r)||r<=0)throw new y("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Wr(r)}var or={};xe(or,{exportToPem:()=>Hg,importFromPem:()=>$g,jwkToPkcs1:()=>Mg,jwkToPkix:()=>Vg,pkcs1ToJwk:()=>Ug,pkixToJwk:()=>Fg});var zo=class extends zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,To(e);let n=Wt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Gr(this),this.iHash.update(e),this}digestInto(e){Gr(this),qr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed: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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Hn=(r,e,t)=>new zo(r,e).update(t).digest();Hn.create=(r,e)=>new zo(r,e);function vg(r,e,t,n){To(r);let o=hu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if($r(s),$r(i),$r(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wt(e),u=Wt(t),f=new Uint8Array(i),l=Hn.create(r,c),h=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:h}}function Ag(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function ec(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=vg(r,e,t,n),f,l=new Uint8Array(4),h=Yr(l),g=new Uint8Array(c.outputLen);for(let d=1,p=0;p<s;d++,p+=c.outputLen){let m=a.subarray(p,p+c.outputLen);h.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(g),m.set(g.subarray(0,m.length)),await fu(o-1,i,()=>{c._cloneInto(f).update(g).digestInto(g);for(let w=0;w<m.length;w++)m[w]^=g[w]})}return Ag(c,u,a,f,g)}var H=Ht(Gu());function _r(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 tr(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 u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function jo(...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 rc(){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=_r(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,_r(s,8)-n}function zu(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=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tr(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 Yu(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 qe(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 yx=Math.log(2);function Xo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function nc(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 Ot(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 qn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return nc(this.items)}},$n=[new Uint8Array([1])],Wu="0123456789";var sn="",lt=new ArrayBuffer(0),oc=new Uint8Array(0),Gn="EndOfContent",Xu="OCTET STRING",Zu="BIT STRING";function Ut(r){var e;return e=class extends r{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?H.BufferSourceConverter.toUint8Array(s.valueHex):oc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",lt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:H.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var kt=class{constructor({blockLength:e=0,error:t=sn,warnings:n=[],valueBeforeDecode:o=oc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=H.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:H.Convert.ToHex(this.valueBeforeDecodeView)}}};kt.NAME="baseBlock";var Oe=class extends kt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Oe.NAME="valueBlock";var Zo=class extends Ut(kt){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?H.BufferSourceConverter.toUint8Array(e.valueHex):oc,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",lt}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=tr(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=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let h=new Uint8Array(f);for(let g=0;g<u.length;g++)h[g]=u[g];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=u[h];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=_r(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Zo.NAME="identificationBlock";var Qo=class extends kt{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=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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=_r(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=tr(this.length,8);if(o.byteLength>127)return this.error="Too big length",lt;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}}};Qo.NAME="lengthBlock";var I={},Ie=class extends kt{constructor({name:e=sn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Zo(o),this.lenBlock=new Qo(o),this.valueBlock=s?new s(o):new Oe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new qn;t||Qu(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?lt: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():H.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Yu(t,n)}};Ie.NAME="BaseBlock";function Qu(r){if(r instanceof I.Constructed)for(let e of r.valueBlock.value)Qu(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Jo=class extends Ie{constructor({value:e=sn,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Jo.NAME="BaseStringBlock";var es=class extends Ut(Oe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};es.NAME="PrimitiveValueBlock";var Ju,ts=class extends Ie{constructor(e={}){super(e,es),this.idBlock.isConstructed=!1}};Ju=ts;I.Primitive=Ju;ts.NAME="PRIMITIVE";function Lg(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 Ds(r,e=0,t=r.length){let n=e,o=new Ie({},Oe),s=new kt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ie;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=I.EndOfContent;break;case 1:c=I.Boolean;break;case 2:c=I.Integer;break;case 3:c=I.BitString;break;case 4:c=I.OctetString;break;case 5:c=I.Null;break;case 6:c=I.ObjectIdentifier;break;case 10:c=I.Enumerated;break;case 12:c=I.Utf8String;break;case 13:c=I.RelativeObjectIdentifier;break;case 14:c=I.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=I.Sequence;break;case 17:c=I.Set;break;case 18:c=I.NumericString;break;case 19:c=I.PrintableString;break;case 20:c=I.TeletexString;break;case 21:c=I.VideotexString;break;case 22:c=I.IA5String;break;case 23:c=I.UTCTime;break;case 24:c=I.GeneralizedTime;break;case 25:c=I.GraphicString;break;case 26:c=I.VisibleString;break;case 27:c=I.GeneralString;break;case 28:c=I.UniversalString;break;case 29:c=I.CharacterString;break;case 30:c=I.BmpString;break;case 31:c=I.DATE;break;case 32:c=I.TimeOfDay;break;case 33:c=I.DateTime;break;case 34:c=I.Duration;break;default:{let u=o.idBlock.isConstructed?new I.Constructed:new I.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?I.Constructed:I.Primitive}return o=Lg(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function an(r){if(!r.byteLength){let e=new Ie({},Oe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ds(H.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function kg(r,e){return r?1:e}var wt=class extends Oe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=H.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;kg(this.isIndefiniteForm,n)>0;){let i=Ds(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Gn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new qn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?lt:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};wt.NAME="ConstructedValueBlock";var ef,rr=class extends Ie{constructor(e={}){super(e,wt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
3
3
  `).map(o=>` ${o}`).join(`
4
4
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
5
  ${e.join(`
6
- `)}`:`${t} :`}};Qu=rr;I.Constructed=Qu;rr.NAME="CONSTRUCTED";var rs=class extends Oe{fromBER(e,t,n){return t}toBER(e){return lt}};rs.override="EndOfContentValueBlock";var Ju,ns=class extends Se{constructor(e={}){super(e,rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Ju=ns;I.EndOfContent=Ju;ns.NAME=Gn;var ef,nr=class extends Se{constructor(e={}){super(e,Oe),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}`}};ef=nr;I.Null=ef;nr.NAME="NULL";var os=class extends Ut(Oe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=H.BufferSourceConverter.toUint8Array(e);return Ot(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,nc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};os.NAME="BooleanValueBlock";var tf,ss=class extends Se{constructor(e={}){super(e,os),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};tf=ss;I.Boolean=tf;ss.NAME="BOOLEAN";var is=class extends Ut(wt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Wu)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?wt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};is.NAME="OctetStringValueBlock";var rf,Dt=class r extends Se{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},is),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ds(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?rr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return H.BufferSourceConverter.concat(e)}};rf=Dt;I.OctetString=rf;Dt.NAME=Wu;var as=class extends Ut(wt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==ju)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=H.BufferSourceConverter.toUint8Array(e);if(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ds(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return wt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return lt;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}}};as.NAME="BitStringValueBlock";var nf,on=class extends Se{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},as),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};nf=on;I.BitString=nf;on.NAME=ju;var of;function Dg(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,u=0,f=c<i?i:c,l=0;for(let h=f;h>=0;h--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=jo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=jo(t,s)),s}function Yu(r){if(r>=$n.length)for(let e=$n.length;e<=r;e++){let t=new Uint8Array([0]),n=$n[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=jo(t,n)),$n.push(n)}return $n[r]}function Pg(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,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var zn=class extends Ut(Oe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=nc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(qu(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?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 u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=Pg(Yu(n),t),i="-";break;default:t=Dg(t,Yu(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=zu.charAt(t[c]));return a===!1&&(i+=zu.charAt(0)),i}};of=zn;zn.NAME="IntegerValueBlock";Object.defineProperty(of.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var sf,me=class r extends Se{constructor(e={}){super(e,zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Xo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Xo();let t=BigInt(e),n=new qn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(H.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${H.Convert.ToHex(a)}`)+t,f=H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};sf=me;I.Integer=sf;me.NAME="INTEGER";var af,cs=class extends me{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};af=cs;I.Enumerated=af;cs.NAME="ENUMERATED";var Yn=class extends Ut(Oe){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=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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));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?(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=_r(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Xo();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=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;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=H.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}}};Yn.NAME="sidBlock";var ls=class extends Oe{constructor({value:e=sn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Yn;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,lt;t.push(o)}return oc(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 Yn;if(o>Number.MAX_SAFE_INTEGER){Xo();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}};ls.NAME="ObjectIdentifierValueBlock";var cf,ct=class extends Se{constructor(e={}){super(e,ls),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};cf=ct;I.ObjectIdentifier=cf;ct.NAME="OBJECT IDENTIFIER";var Wn=class extends Ut(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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));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?(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=_r(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=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;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=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Wn.NAME="relativeSidBlock";var us=class extends Oe{constructor({value:e=sn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;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,lt;n.push(s)}return oc(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 Wn;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}};us.NAME="RelativeObjectIdentifierValueBlock";var lf,fs=class extends Se{constructor(e={}){super(e,us),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};lf=fs;I.RelativeObjectIdentifier=lf;fs.NAME="RelativeObjectIdentifier";var uf,xe=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};uf=xe;I.Sequence=uf;xe.NAME="SEQUENCE";var ff,hs=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ff=hs;I.Set=ff;hs.NAME="SET";var ds=class extends Ut(Oe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=sn}toJSON(){return{...super.toJSON(),value:this.value}}};ds.NAME="StringValueBlock";var ps=class extends ds{};ps.NAME="SimpleStringValueBlock";var He=class extends Jo{constructor({...e}={}){super(e,ps)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.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}};He.NAME="SIMPLE STRING";var ms=class extends He{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ms.NAME="Utf8StringValueBlock";var hf,Pt=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};hf=Pt;I.Utf8String=hf;Pt.NAME="UTF8String";var gs=class extends He{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};gs.NAME="BmpStringValueBlock";var df,ys=class extends gs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};df=ys;I.BmpString=df;ys.NAME="BMPString";var ws=class extends He{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=tr(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}};ws.NAME="UniversalStringValueBlock";var pf,bs=class extends ws{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};pf=bs;I.UniversalString=pf;bs.NAME="UniversalString";var mf,Es=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};mf=Es;I.NumericString=mf;Es.NAME="NumericString";var gf,xs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};gf=xs;I.PrintableString=gf;xs.NAME="PrintableString";var yf,vs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};yf=vs;I.TeletexString=yf;vs.NAME="TeletexString";var wf,As=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};wf=As;I.VideotexString=wf;As.NAME="VideotexString";var bf,Rs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};bf=Rs;I.IA5String=bf;Rs.NAME="IA5String";var Ef,_s=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ef=_s;I.GraphicString=Ef;_s.NAME="GraphicString";var xf,jn=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};xf=jn;I.VisibleString=xf;jn.NAME="VisibleString";var vf,Ss=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};vf=Ss;I.GeneralString=vf;Ss.NAME="GeneralString";var Af,Is=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Af=Is;I.CharacterString=Af;Is.NAME="CharacterString";var Rf,Xn=class extends jn{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,H.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]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(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}}};Rf=Xn;I.UTCTime=Rf;Xn.NAME="UTCTime";var _f,Bs=class extends Xn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.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 l=1,h=n.indexOf("+"),g="";if(h===-1&&(h=n.indexOf("-"),l=-1),h!==-1){if(g=n.substring(h+1),n=n.substring(0,h),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(g.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,g.length===4){if(d=parseInt(g.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-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,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};_f=Bs;I.GeneralizedTime=_f;Bs.NAME="GeneralizedTime";var Sf,Ts=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Sf=Ts;I.DATE=Sf;Ts.NAME="DATE";var If,Cs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};If=Cs;I.TimeOfDay=If;Cs.NAME="TimeOfDay";var Bf,Ns=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Bf=Ns;I.DateTime=Bf;Ns.NAME="DateTime";var Tf,Ls=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Tf=Ls;I.Duration=Tf;Ls.NAME="Duration";var Cf,ks=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Cf=ks;I.TIME=Cf;ks.NAME="TIME";function Ug(r){let{result:e}=an(r),t=e.valueBlock.value;return{n:K(bt(t[1].toBigInt()),"base64url"),e:K(bt(t[2].toBigInt()),"base64url"),d:K(bt(t[3].toBigInt()),"base64url"),p:K(bt(t[4].toBigInt()),"base64url"),q:K(bt(t[5].toBigInt()),"base64url"),dp:K(bt(t[6].toBigInt()),"base64url"),dq:K(bt(t[7].toBigInt()),"base64url"),qi:K(bt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Mg(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 y("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new xe({value:[new me({value:0}),me.fromBigInt(Et(D(r.n,"base64url"))),me.fromBigInt(Et(D(r.e,"base64url"))),me.fromBigInt(Et(D(r.d,"base64url"))),me.fromBigInt(Et(D(r.p,"base64url"))),me.fromBigInt(Et(D(r.q,"base64url"))),me.fromBigInt(Et(D(r.dp,"base64url"))),me.fromBigInt(Et(D(r.dq,"base64url"))),me.fromBigInt(Et(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Fg(r){let{result:e}=an(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:K(bt(t[0].toBigInt()),"base64url"),e:K(bt(t[1].toBigInt()),"base64url")}}function Vg(r){if(r.n==null||r.e==null)throw new y("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new xe({value:[new xe({value:[new ct({value:"1.2.840.113549.1.1.1"}),new nr]}),new on({valueHex:new xe({value:[me.fromBigInt(Et(D(r.n,"base64url"))),me.fromBigInt(Et(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function Et(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var Kg=16,ic=32,ac=1e4;async function Hg(r,e){let t=Me.get(),o=new xe({value:[new me({value:0}),new xe({value:[new ct({value:"1.2.840.113549.1.1.1"}),new nr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=yt(Kg),a=await tc(Xr,e,i,{c:ac,dkLen:ic}),c=yt(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new xe({value:[new Dt({valueHex:i}),new me({value:ac}),new me({value:ic}),new xe({value:[new ct({value:"1.2.840.113549.2.11"}),new nr]})]}),h=new xe({value:[new ct({value:"1.2.840.113549.1.5.13"}),new xe({value:[new xe({value:[new ct({value:"1.2.840.113549.1.5.12"}),l]}),new xe({value:[new ct({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new xe({value:[h,new Dt({valueHex:f})]}).toBER(),p=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...K(p,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function $g(r,e){let t=Me.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=an(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=qg(s),l=await tc(Xr,e,a,{c,dkLen:u}),h=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),g=Zn(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,f)),{result:d}=an(g);n=Nf(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=an(o);n=Nf(s)}else throw new y("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return cc(n)}function qg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new y("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new y("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Zn(s.valueBlock.value[0].getValue()),a=ac,c=ic;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 y("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new y("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Zn(u.valueBlock.value[1].getValue());return{cipherText:Zn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Nf(r){return Zn(r.valueBlock.value[2].getValue())}function Zn(r){return new Uint8Array(r,0,r.byteLength)}async function Lf(r){let e=await Me.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Pf(e);return{privateKey:t[0],publicKey:t[1]}}async function lc(r){let t=[await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Gg(r)],n=await Pf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function kf(r,e){let t=await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Me.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Df(r,e,t){let n=await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Me.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Pf(r){if(r.privateKey==null||r.publicKey==null)throw new y("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Me.get().subtle.exportKey("jwk",r.privateKey),Me.get().subtle.exportKey("jwk",r.publicKey)])}async function Gg(r){return Me.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ps(r){if(r.kty!=="RSA")throw new y("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new y("invalid key modulus","ERR_INVALID_KEY_MODULUS");return D(r.n,"base64url").length*8}var Jn=8192,Qn=class{_key;constructor(e){this._key=e}verify(e,t){return Df(this._key,t,e)}marshal(){return or.jwkToPkix(this._key)}get bytes(){return mt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},cn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return yt(16)}sign(e){return kf(this._key,e)}get public(){if(this._publicKey==null)throw new y("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Qn(this._publicKey)}marshal(){return or.jwkToPkcs1(this._key)}get bytes(){return gt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return or.exportToPem(this,e);if(t==="libp2p-key")return en(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function cc(r){let e=or.pkcs1ToJwk(r);if(Ps(e)>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await lc(e);return new cn(t.privateKey,t.publicKey)}function Yg(r){let e=or.pkixToJwk(r);if(Ps(e)>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Qn(e)}async function Wg(r){if(Ps(r)>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await lc(r);return new cn(e.privateKey,e.publicKey)}async function jg(r){if(r>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Lf(r);return new cn(e.privateKey,e.publicKey)}var mc={};Ee(mc,{Secp256k1PrivateKey:()=>to,Secp256k1PublicKey:()=>eo,generateKeyPair:()=>c0,unmarshalSecp256k1PrivateKey:()=>i0,unmarshalSecp256k1PublicKey:()=>a0});var Xg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=new Uint32Array(64),fc=class extends jr{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[7]|0}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 l=0;l<16;l++,t+=4)ir[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=ir[l-15],g=ir[l-2],d=ot(h,7)^ot(h,18)^h>>>3,p=ot(g,17)^ot(g,19)^g>>>10;ir[l]=p+ir[l-7]+d+ir[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let h=ot(a,6)^ot(a,11)^ot(a,25),g=f+h+fu(a,c,u)+Xg[l]+ir[l]|0,p=(ot(n,2)^ot(n,13)^ot(n,22))+hu(n,o,s)|0;f=u,u=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+p|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,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Of=Lo(()=>new fc);function Zg(r){let e=Mn(r);pt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Qg,hexToBytes:Jg}=Po,Sr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Sr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Qg(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Sr,t=typeof r=="string"?Jg(r):r;Zr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Sr._parseInt(t.subarray(2)),{d:i,l:a}=Sr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Mt=BigInt(0),rt=BigInt(1),qx=BigInt(2),Uf=BigInt(3),Gx=BigInt(4);function e0(r){let e=Zg(r),{Fp:t}=e,n=e.toBytes||((d,p,m)=>{let w=p.toAffine();return Tt(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(d=>{let p=d.subarray(1),m=t.fromBytes(p.subarray(0,t.BYTES)),w=t.fromBytes(p.subarray(t.BYTES,2*t.BYTES));return{x:m,y:w}});function s(d){let{a:p,b:m}=e,w=t.sqr(d),x=t.mul(w,d);return t.add(t.add(x,t.mul(d,p)),m)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Mt<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:p,nByteLength:m,wrapPrivateKey:w,n:x}=e;if(p&&typeof d!="bigint"){if(Zt(d)&&(d=It(d)),typeof d!="string"||!p.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(ae("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return w&&(b=Z(b,x)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,w){if(this.px=p,this.py=m,this.pz=w,p==null||!t.isValid(p))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(p){let{x:m,y:w}=p||{};if(!p||!t.isValid(m)||!t.isValid(w))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let x=b=>t.eql(b,t.ZERO);return x(m)&&x(w)?l.ZERO:new l(m,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=t.invertBatch(p.map(w=>w.pz));return p.map((w,x)=>w.toAffine(m[x])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(o(ae("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!t.isValid(p)||!t.isValid(m))throw new Error("bad point: x or y not FE");let w=t.sqr(m),x=s(p);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(t.isOdd)return!t.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.eql(t.mul(m,v),t.mul(b,x)),C=t.eql(t.mul(w,v),t.mul(A,x));return S&&C}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:p,b:m}=e,w=t.mul(m,Uf),{px:x,py:b,pz:A}=this,v=t.ZERO,S=t.ZERO,C=t.ZERO,N=t.mul(x,x),q=t.mul(b,b),G=t.mul(A,A),U=t.mul(x,b);return U=t.add(U,U),C=t.mul(x,A),C=t.add(C,C),v=t.mul(p,C),S=t.mul(w,G),S=t.add(v,S),v=t.sub(q,S),S=t.add(q,S),S=t.mul(v,S),v=t.mul(U,v),C=t.mul(w,C),G=t.mul(p,G),U=t.sub(N,G),U=t.mul(p,U),U=t.add(U,C),C=t.add(N,N),N=t.add(C,N),N=t.add(N,G),N=t.mul(N,U),S=t.add(S,N),G=t.mul(b,A),G=t.add(G,G),N=t.mul(G,U),v=t.sub(v,N),C=t.mul(G,q),C=t.add(C,C),C=t.add(C,C),new l(v,S,C)}add(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.ZERO,C=t.ZERO,N=t.ZERO,q=e.a,G=t.mul(e.b,Uf),U=t.mul(m,b),he=t.mul(w,A),le=t.mul(x,v),Je=t.add(m,w),R=t.add(b,A);Je=t.mul(Je,R),R=t.add(U,he),Je=t.sub(Je,R),R=t.add(m,x);let L=t.add(b,v);return R=t.mul(R,L),L=t.add(U,le),R=t.sub(R,L),L=t.add(w,x),S=t.add(A,v),L=t.mul(L,S),S=t.add(he,le),L=t.sub(L,S),N=t.mul(q,R),S=t.mul(G,le),N=t.add(S,N),S=t.sub(he,N),N=t.add(he,N),C=t.mul(S,N),he=t.add(U,U),he=t.add(he,U),le=t.mul(q,le),R=t.mul(G,R),he=t.add(he,le),le=t.sub(U,le),le=t.mul(q,le),R=t.add(R,le),U=t.mul(he,R),C=t.add(C,U),U=t.mul(L,R),S=t.mul(Je,S),S=t.sub(S,U),U=t.mul(Je,he),N=t.mul(L,N),N=t.add(N,U),new l(S,C,N)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return g.wNAFCached(this,u,p,m=>{let w=t.invertBatch(m.map(x=>x.pz));return m.map((x,b)=>x.toAffine(w[b])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===Mt)return m;if(a(p),p===rt)return this;let{endo:w}=e;if(!w)return g.unsafeLadder(this,p);let{k1neg:x,k1:b,k2neg:A,k2:v}=w.splitScalar(p),S=m,C=m,N=this;for(;b>Mt||v>Mt;)b&rt&&(S=S.add(N)),v&rt&&(C=C.add(N)),N=N.double(),b>>=rt,v>>=rt;return x&&(S=S.negate()),A&&(C=C.negate()),C=new l(t.mul(C.px,w.beta),C.py,C.pz),S.add(C)}multiply(p){a(p);let m=p,w,x,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:S,k2:C}=b.splitScalar(m),{p:N,f:q}=this.wNAF(v),{p:G,f:U}=this.wNAF(C);N=g.constTimeNegate(A,N),G=g.constTimeNegate(S,G),G=new l(t.mul(G.px,b.beta),G.py,G.pz),w=N.add(G),x=q.add(U)}else{let{p:A,f:v}=this.wNAF(m);w=A,x=v}return l.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(p,m,w){let x=l.BASE,b=(v,S)=>S===Mt||S===rt||!v.equals(x)?v.multiplyUnsafe(S):v.multiply(S),A=b(this,m).add(b(p,w));return A.is0()?void 0:A}toAffine(p){let{px:m,py:w,pz:x}=this,b=this.is0();p==null&&(p=b?t.ONE:t.inv(x));let A=t.mul(m,p),v=t.mul(w,p),S=t.mul(x,p);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=e;if(p===rt)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=e;return p===rt?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return It(this.toRawBytes(p))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,g=Mo(l,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function t0(r){let e=Mn(r);return pt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Mf(r){let e=t0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(R){return Mt<R&&R<t.ORDER}function a(R){return Z(R,n)}function c(R){return Oo(R,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=e0({...e,toBytes(R,L,M){let _=L.toAffine(),E=t.toBytes(_.x),T=Tt;return M?T(Uint8Array.from([L.hasEvenY()?2:3]),E):T(Uint8Array.from([4]),E,t.toBytes(_.y))},fromBytes(R){let L=R.length,M=R[0],_=R.subarray(1);if(L===o&&(M===2||M===3)){let E=Bt(_);if(!i(E))throw new Error("Point is not on curve");let T=l(E),k;try{k=t.sqrt(T)}catch(V){let Y=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+Y)}let P=(k&rt)===rt;return(M&1)===1!==P&&(k=t.neg(k)),{x:E,y:k}}else if(L===s&&M===4){let E=t.fromBytes(_.subarray(0,t.BYTES)),T=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:E,y:T}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),g=R=>It(Jt(R,e.nByteLength));function d(R){let L=n>>rt;return R>L}function p(R){return d(R)?a(-R):R}let m=(R,L,M)=>Bt(R.slice(L,M));class w{constructor(L,M,_){this.r=L,this.s=M,this.recovery=_,this.assertValidity()}static fromCompact(L){let M=e.nByteLength;return L=ae("compactSignature",L,M*2),new w(m(L,0,M),m(L,M,2*M))}static fromDER(L){let{r:M,s:_}=Sr.toSig(ae("DER",L));return new w(M,_)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:_,recovery:E}=this,T=C(ae("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let k=E===2||E===3?M+e.n:M;if(k>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=E&1?"03":"02",F=u.fromHex(P+g(k)),V=c(k),Y=a(-T*V),$=a(_*V),z=u.BASE.multiplyAndAddUnsafe(F,Y,$);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return wr(this.toDERHex())}toDERHex(){return Sr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return wr(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let x={isValidPrivateKey(R){try{return f(R),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let R=Ta(e.n);return Au(e.randomBytes(R),e.n)},precompute(R=8,L=u.BASE){return L._setWindowSize(R),L.multiply(BigInt(3)),L}};function b(R,L=!0){return u.fromPrivateKey(R).toRawBytes(L)}function A(R){let L=Zt(R),M=typeof R=="string",_=(L||M)&&R.length;return L?_===o||_===s:M?_===2*o||_===2*s:R instanceof u}function v(R,L,M=!0){if(A(R))throw new Error("first arg must be private key");if(!A(L))throw new Error("second arg must be public key");return u.fromHex(L).multiply(f(R)).toRawBytes(M)}let S=e.bits2int||function(R){let L=Bt(R),M=R.length*8-e.nBitLength;return M>0?L>>BigInt(M):L},C=e.bits2int_modN||function(R){return a(S(R))},N=Un(e.nBitLength);function q(R){if(typeof R!="bigint")throw new Error("bigint expected");if(!(Mt<=R&&R<N))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Jt(R,e.nByteLength)}function G(R,L,M=U){if(["recovered","canonical"].some(oe=>oe in M))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:E}=e,{lowS:T,prehash:k,extraEntropy:P}=M;T==null&&(T=!0),R=ae("msgHash",R),k&&(R=ae("prehashed msgHash",_(R)));let F=C(R),V=f(L),Y=[q(V),q(F)];if(P!=null&&P!==!1){let oe=P===!0?E(t.BYTES):P;Y.push(ae("extraEntropy",oe))}let $=Tt(...Y),z=F;function de(oe){let ve=S(oe);if(!h(ve))return;let Ae=c(ve),ge=u.BASE.multiply(ve).toAffine(),Ne=a(ge.x);if(Ne===Mt)return;let vt=a(Ae*a(z+Ne*V));if(vt===Mt)return;let mr=(ge.x===Ne?0:2)|Number(ge.y&rt),Ln=vt;return T&&d(vt)&&(Ln=p(vt),mr^=1),new w(Ne,Ln,mr)}return{seed:$,k2sig:de}}let U={lowS:e.lowS,prehash:!1},he={lowS:e.lowS,prehash:!1};function le(R,L,M=U){let{seed:_,k2sig:E}=G(R,L,M),T=e;return _a(T.hash.outputLen,T.nByteLength,T.hmac)(_,E)}u.BASE._setWindowSize(8);function Je(R,L,M,_=he){let E=R;if(L=ae("msgHash",L),M=ae("publicKey",M),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:T,prehash:k}=_,P,F;try{if(typeof E=="string"||Zt(E))try{P=w.fromDER(E)}catch(ge){if(!(ge instanceof Sr.Err))throw ge;P=w.fromCompact(E)}else if(typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint"){let{r:ge,s:Ne}=E;P=new w(ge,Ne)}else throw new Error("PARSE");F=u.fromHex(M)}catch(ge){if(ge.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&P.hasHighS())return!1;k&&(L=e.hash(L));let{r:V,s:Y}=P,$=C(L),z=c(Y),de=a($*z),oe=a(V*z),ve=u.BASE.multiplyAndAddUnsafe(F,de,oe)?.toAffine();return ve?a(ve.x)===V:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:le,verify:Je,ProjectivePoint:u,Signature:w,utils:x}}function r0(r){return{hash:r,hmac:(e,...t)=>Hn(r,e,No(...t)),randomBytes:Wr}}function Ff(r,e){let t=n=>Mf({...r,...r0(n)});return Object.freeze({...t(e),create:t})}var Hf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Vf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),n0=BigInt(1),hc=BigInt(2),Kf=(r,e)=>(r+e/hc)/e;function o0(r){let e=Hf,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ee(f,t,e)*f%e,h=ee(l,t,e)*f%e,g=ee(h,hc,e)*u%e,d=ee(g,o,e)*g%e,p=ee(d,s,e)*d%e,m=ee(p,a,e)*p%e,w=ee(m,c,e)*m%e,x=ee(w,a,e)*p%e,b=ee(x,t,e)*f%e,A=ee(b,i,e)*d%e,v=ee(A,n,e)*u%e,S=ee(v,hc,e);if(!dc.eql(dc.sqr(S),r))throw new Error("Cannot find square root");return S}var dc=Uo(Hf,void 0,void 0,{sqrt:o0}),ut=Ff({a:BigInt(0),b:BigInt(7),Fp:dc,n:Vf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Vf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-n0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Kf(s*r,e),c=Kf(-n*r,e),u=Z(r-a*t-c*o,e),f=Z(-a*n-c*s,e),l=u>i,h=f>i;if(l&&(u=e-u),h&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},Of),ev=BigInt(0);var tv=ut.ProjectivePoint;function $f(){return ut.utils.randomPrivateKey()}function qf(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(et(t))return t.then(({digest:n})=>ut.sign(n,r).toDERRawBytes()).catch(n=>{throw new y(String(n),"ERR_INVALID_INPUT")});try{return ut.sign(t.digest,r).toDERRawBytes()}catch(n){throw new y(String(n),"ERR_INVALID_INPUT")}}function Gf(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(et(n))return n.then(({digest:o})=>ut.verify(e,o,r)).catch(o=>{throw new y(String(o),"ERR_INVALID_INPUT")});try{return ut.verify(e,n.digest,r)}catch(o){throw new y(String(o),"ERR_INVALID_INPUT")}}function zf(r){return ut.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Yf(r){try{ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}function pc(r){try{ut.ProjectivePoint.fromHex(r)}catch(e){throw new y(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Wf(r){try{return ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}var eo=class{_key;constructor(e){pc(e),this._key=e}verify(e,t){return Gf(this._key,t,e)}marshal(){return zf(this._key)}get bytes(){return mt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}},to=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Wf(e),Yf(this._key),pc(this._publicKey)}sign(e){return qf(this._key,e)}get public(){return new eo(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return en(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function i0(r){return new to(r)}function a0(r){return new eo(r)}async function c0(){let r=$f();return new to(r)}var ar={rsa:uc,ed25519:ec,secp256k1:mc};function gc(r){let e=Object.keys(ar).join(" / ");return new y(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function yc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ar[r];throw gc(r)}async function jf(r,e){return yc(r).generateKeyPair(e??2048)}function ro(r){let e=mt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return ar.rsa.unmarshalRsaPublicKey(t);case te.Ed25519:return ar.ed25519.unmarshalEd25519PublicKey(t);case te.Secp256k1:return ar.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw gc(e.Type??"unknown")}}function Xf(r,e){return e=(e??"rsa").toLowerCase(),yc(e),r.bytes}async function no(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return ar.rsa.unmarshalRsaPrivateKey(t);case te.Ed25519:return ar.ed25519.unmarshalEd25519PrivateKey(t);case te.Secp256k1:return ar.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw gc(e.Type??"RSA")}}function Zf(r,e){return e=(e??"rsa").toLowerCase(),yc(e),r.bytes}var je=Ht(rh(),1);je.default.formatters.b=r=>r==null?"undefined":ne.baseEncode(r);je.default.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);je.default.formatters.m=r=>r==null?"undefined":Pn.baseEncode(r);je.default.formatters.p=r=>r==null?"undefined":r.toString();je.default.formatters.c=r=>r==null?"undefined":r.toString();je.default.formatters.k=r=>r==null?"undefined":r.toString();je.default.formatters.a=r=>r==null?"undefined":r.toString();function x0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ms(){return{forComponent(r){return v0(r)}}}function v0(r){let e=x0(`${r}:trace`);return je.default.enabled(`${r}:trace`)&&je.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,je.default)(`${r}:trace`)),Object.assign((0,je.default)(r),{error:(0,je.default)(`${r}:error`),trace:e})}var A0=Symbol.for("nodejs.util.inspect.custom"),nh=Object.values(Yt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Yt.identity.decoder),oh=114,wc=36,bc=37,oo=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Wi]=!0;toString(){return this.string==null&&(this.string=ne.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return nt.createV1(oh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return we(e).equals(this);if(e?.multihash?.bytes!=null)return ie(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[A0](){return`PeerId(${this.toString()})`}},Br=class extends oo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends oo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Cr=class extends oo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function sh(r){if(r.type==="RSA")return new Br(r);if(r.type==="Ed25519")return new Tr(r);if(r.type==="secp256k1")return new Cr(r);throw new y("Not a PeerId","ERR_INVALID_PARAMETERS")}function we(r,e){if(e=e??nh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=gr(ne.decode(`z${r}`));return r.startsWith("12D")?new Tr({multihash:t}):r.startsWith("16U")?new Cr({multihash:t}):new Br({multihash:t})}return hn(nh.decode(r))}function hn(r){try{let e=gr(r);if(e.code===zt.code){if(e.digest.length===wc)return new Tr({multihash:e});if(e.digest.length===bc)return new Cr({multihash:e})}if(e.code===Re.code)return new Br({multihash:e})}catch{return R0(nt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function R0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==oh)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Re.code)return new Br({multihash:r.multihash});if(e.code===zt.code){if(e.digest.length===wc)return new Tr({multihash:r.multihash});if(e.digest.length===bc)return new Cr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function dn(r,e){return r.length===wc?new Tr({multihash:dt(zt.code,r),privateKey:e}):r.length===bc?new Cr({multihash:dt(zt.code,r),privateKey:e}):new Br({multihash:await Re.digest(r),publicKey:r,privateKey:e})}function pn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return pn(this.map.entries(),e=>[we(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,we(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return pn(this.map.keys(),e=>we(e))}values(){return this.map.values()}get size(){return this.map.size}};var ft=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 pn(this.set.entries(),e=>{let t=we(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=we(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pn(this.set.values(),e=>we(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var ah=Symbol.for("@achingbrain/uint8arraylist");function ih(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 Fs(r){return!!r?.[ah]}var be=class r{bufs;length;[ah]=!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(Fs(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Fs(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=ih(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ih(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(Fs(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 _e(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:_e(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 u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){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(!Fs(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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let h=u;h>=0;h--){let g=this.get(l+h);if(n[h]!==g){f=Math.max(1,h-a[g]);break}}if(f===0)return l}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=Le(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=_t(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=_t(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=_t(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=Le(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=_t(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=_t(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=_t(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=_t(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=_t(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var ch=async()=>{let r=await jf("Ed25519"),e=await _0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function _0(r){return dn(Xf(r.public),Zf(r))}var lh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var so;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(so||(so={}));var mn=class r{static createFromProtobuf=async e=>{let t=so.decode(e),n=await dn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=uh(n,o,s),c=await(await no(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new y("envelope signature is not valid for the given domain",lh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=so.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ie(this.marshal(),e.marshal())}async validate(e){let t=uh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return ro(this.peerId.publicKey).verify(t.subarray(),this.signature)}},uh=(r,e,t)=>{let n=D(r),o=De(n.byteLength),s=De(e.length),i=De(t.length);return new be(o,n,s,e,i,t)};function fh(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 Vs=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",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(f===void 0)break;if(s*=e,s+=f,s>u||(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 hh=45,S0=15,gn=new Vs;function Ec(r){if(!(r.length>S0))return gn.new(r).parseWith(()=>gn.readIPv4Addr())}function xc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>hh))return gn.new(r).parseWith(()=>gn.readIPv6Addr())}function Ks(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>hh))return gn.new(r).parseWith(()=>gn.readIPAddr())}var E1=parseInt("0xFFFF",16),x1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function yn(r){return!!Ec(r)}function wn(r){return!!xc(r)}function Hs(r){return!!Ks(r)}var mh=yn,N0=wn,vc=function(r){let e=0;if(r=r.toString().trim(),mh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(N0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=mh(t[n]),i;s&&(i=vc(t[n]),t[n]=K(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let 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++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},gh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var bn={},Ac={},k0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];k0.forEach(r=>{let e=D0(...r);Ac[e.code]=e,bn[e.name]=e});function D0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(Ac[r]!=null)return Ac[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(bn[r]!=null)return bn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var oA=X("ip4"),sA=X("ip6"),iA=X("ipcidr");function _c(r,e){switch(X(r).code){case 4:case 41:return O0(e);case 42:return bh(e);case 6:case 273:case 33:case 132:return xh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return bh(e);case 421:return V0(e);case 444:return Eh(e);case 445:return Eh(e);case 466:return F0(e);default:return K(e,"base16")}}function Sc(r,e){switch(X(r).code){case 4:return yh(e);case 41:return yh(e);case 42:return wh(e);case 6:case 273:case 33:case 132:return Ic(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return wh(e);case 421:return U0(e);case 444:return K0(e);case 445:return H0(e);case 466:return M0(e);default:return D(e,"base16")}}var Rc=Object.values(Yt).map(r=>r.decoder),P0=function(){let r=Rc[0].or(Rc[1]);return Rc.slice(2).forEach(e=>r=r.or(e)),r}();function yh(r){if(!Hs(r))throw new Error("invalid ip address");return vc(r)}function O0(r){let e=gh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Hs(e))throw new Error("invalid ip address");return e}function Ic(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function xh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function wh(r){let e=D(r),t=Uint8Array.from(De(e.length));return _e([t,e],t.length+e.length)}function bh(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return K(r)}function U0(r){let e;r[0]==="Q"||r[0]==="1"?e=gr(ne.decode(`z${r}`)).bytes:e=nt.parse(r).multihash.bytes;let t=Uint8Array.from(De(e.length));return _e([t,e],t.length+e.length)}function M0(r){let e=P0.decode(r),t=Uint8Array.from(De(e.length));return _e([t,e],t.length+e.length)}function F0(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+K(t,"base64url")}function V0(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return K(t,"base58btc")}function K0(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=Ge.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=Ic(n);return _e([t,o],t.length+o.length)}function H0(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=Ge.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=Ic(n);return _e([t,o],t.length+o.length)}function Eh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=K(e,"base32"),o=xh(t);return`${n}:${o}`}function vh(r){r=Bc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Rh("invalid address: "+r);if(a.path===!0){n=Bc(o.slice(s).join("/")),e.push([a.code,Sc(a.code,n)]),t.push([a.code,n]);break}let c=Sc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,_c(a.code,c)])}return{string:Ah(t),bytes:Cc(e),tuples:e,stringTuples:t,path:n}}function Tc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=pe(s),a=X(s),c=$0(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Rh("Invalid address Uint8Array: "+K(r,"base16"));e.push([s,u]);let f=_c(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Ah(t),tuples:e,stringTuples:t,path:n}}function Ah(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Bc(e.join("/"))}function Cc(r){return _e(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(De(t.code));return e.length>1&&e[1]!=null&&(n=_e([n,e[1]])),n}))}function $0(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function Bc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Rh(r){return new Error("Error parsing address: "+r)}var q0=Symbol.for("nodejs.util.inspect.custom"),Nc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),G0=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],$s=class r{bytes;#e;#t;#s;#a;[Nc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Tc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=vh(e)}else if(cr(e))t=Tc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[g,d]of this.stringTuples())g===l.code&&(s=`%${d??""}`),G0.includes(g)&&(t=i.name,o=443,n=`${d??""}${s}`,e=g===f.code?6:4),(g===i.code||g===a.code)&&(t=X(g).name,o=parseInt(d??"")),(g===c.code||g===u.code)&&(t=X(g).name,n=`${d??""}${s}`,e=g===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Cc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===bn.p2p.code&&e.push([n,o]),n===bn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?K(ne.decode(`z${n}`),"base58btc"):K(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=En.get(t.name);if(n==null)throw new y(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>re(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[q0](){return`Multiaddr(${this.#e})`}};var En=new Map;function cr(r){return!!r?.[Nc]}function re(r){return new $s(r)}var _h="libp2p-peer-record",Sh=Uint8Array.from([3,1]);var io;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Ve(s,n.codec()),n.decode=s=>Fe(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Ve(n,r.codec()),r.decode=n=>Fe(n,r.codec())})(io||(io={}));var Nr=class r{static createFromProtobuf=e=>{let t=io.decode(e),n=hn(t.peerId),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=_h;static CODEC=Sh;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=io.encode({peerId:this.peerId.toBytes(),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||!fh(this.multiaddrs,e.multiaddrs))}};function z0(r){return r[Symbol.asyncIterator]!=null}function Y0(r){if(z0(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 ao=Y0;var kc=Ht(Bh(),1);var lo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Dc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Th=r=>globalThis.DOMException===void 0?new Dc(r):new DOMException(r),Ch=r=>{let e=r.reason===void 0?Th("This operation was aborted."):r.reason;return e instanceof Error?e:Th(e)};function uo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(Ch(h)),h.addEventListener("abort",()=>{f(Ch(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new lo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Pc(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 fo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Pc(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var lr=class extends kc.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:fo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#R(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=uo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof lo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var ur={},xn=r=>{r.addEventListener("message",e=>{xn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{xn.dispatchEvent("message",r,e)})};xn.addEventListener=(r,e)=>{ur[r]==null&&(ur[r]=[]),ur[r].push(e)};xn.removeEventListener=(r,e)=>{ur[r]!=null&&(ur[r]=ur[r].filter(t=>t===e))};xn.dispatchEvent=function(r,e,t){ur[r]!=null&&ur[r].forEach(n=>n(e,t))};var Oc=xn;var Uc="lock:worker:request-read",Mc="lock:worker:release-read",Fc="lock:master:grant-read",Vc="lock:worker:request-write",Kc="lock:worker:release-write",Hc="lock:master:grant-write";var Nh=(r=21)=>Math.random().toString().substring(2);var Lh=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},kh=(r,e,t,n)=>async()=>{let o=Nh();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},X0={singleProcess:!1},Dh=r=>{if(r=Object.assign({},X0,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Oc.addEventListener("message",Lh(t,"requestReadLock",Uc,Mc,Fc)),Oc.addEventListener("message",Lh(t,"requestWriteLock",Vc,Kc,Hc)),t}return{isWorker:!0,readLock:t=>kh(t,Uc,Fc,Mc),writeLock:t=>kh(t,Vc,Hc,Kc)}};var Lr={},fr;async function $c(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>uo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Z0=(r,e)=>{if(fr.isWorker===!0)return{readLock:fr.readLock(r,e),writeLock:fr.writeLock(r,e)};let t=new lr({concurrency:1}),n;return{async readLock(){if(n!=null)return $c(n,e);n=new lr({concurrency:e.concurrency,autoStart:!1});let o=n,s=$c(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,$c(t,e)}}},Q0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function qc(r){let e=Object.assign({},Q0,r);return fr==null&&(fr=Dh(e),fr.isWorker!==!0&&(fr.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),fr.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=Z0(e.name,e)),Lr[e.name]}var Ie={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var vn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ve(i,o.codec()),o.decode=i=>Fe(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),zs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=zs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ve(i,o.codec()),o.decode=i=>Fe(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Gs.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Gs.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Ve(o,r.codec()),r.decode=o=>Fe(o,r.codec())})(vn||(vn={}));var Gs;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(Gs||(Gs={}));var zs;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(zs||(zs={}));function An(r,e){let t=vn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=sh({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",Ph=new TextEncoder().encode(Ft),Ys=Ph[0],kr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(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]!==Ys)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}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=Ph),this._buf[0]!==Ys){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ys,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ys;)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(Ft).slice(1)}type(){return J0(this.baseNamespace())}name(){return ey(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?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(),...ty(e.map(t=>t.namespaces()))])}};function J0(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function ey(r){let e=r.split(":");return e[e.length-1]}function ty(r){return[].concat(...r)}var Gc="/peers/";function Rn(r){if(!Ro(r)||r.type==null)throw new y("Invalid PeerId",Ie.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new kr(`${Gc}${e}`)}async function Oh(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=re(o.multiaddr)),!cr(o.multiaddr))throw new y("Multiaddr was invalid",Ie.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function js(r,e,t,n){if(e==null)throw new y("Invalid PeerData",Ie.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!ie(e.publicKey,r.publicKey))throw new y("publicKey bytes do not match peer id publicKey bytes",Ie.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new y("peer id did not match existing peer id",Ie.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ws(l,{validate:Uh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ws(l,{validate:Mh,map:Fh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,g]of l)g==null?a.delete(h):a.set(h,g);a=Ws([...a.entries()],{validate:Uh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[g,d]of l)d==null?h.delete(g):h.set(g,d);c=Ws([...h.entries()],{validate:Mh,map:Fh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Oh(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,h)=>l.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function Ws(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 Uh(r,e){if(typeof r!="string")throw new y("Metadata key must be a string",Ie.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new y("Metadata value must be a Uint8Array",Ie.ERR_INVALID_PARAMETERS)}function Mh(r,e){if(typeof r!="string")throw new y("Tag name must be a string",Ie.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new y("Tag value must be an integer",Ie.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new y("Tag value must be between 0-100",Ie.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new y("Tag ttl must be an integer",Ie.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new y("Tag ttl must be between greater than 0",Ie.ERR_INVALID_PARAMETERS)}}function Fh(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Xs(r,e,t){let n=r.toString().split("/")[2],o=Ge.decode(n),s=hn(o),i=t.get(s);if(i!=null)return i;let a=An(s,e);return t.set(s,a),a}function ry(r,e){return r==null?{}:{prefix:Gc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Xs(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Xs(n.key,n.value,e),Xs(o.key,o.value,e)))}}var Zs=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=qc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Rn(e))}async delete(e){if(this.peerId.equals(e))throw new y("Cannot delete self peer",Ie.ERR_INVALID_PARAMETERS);await this.datastore.delete(Rn(e))}async load(e){let t=await this.datastore.get(Rn(e));return An(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(ry(e??{},t))){let s=Xs(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Rn(e)),n=An(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=vn.encode(t);return n!=null&&ie(s,n)?{peer:An(e,s),previous:o,updated:!1}:(await this.datastore.put(Rn(e),s),{peer:An(e,s),previous:o,updated:!0})}};var Qs=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 Zs(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await ao(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mn.openAndCertify(e,Nr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Nr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mn.createFromProtobuf(s.peerRecordEnvelope),a=Nr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!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 ny(r){return r[Symbol.asyncIterator]!=null}function oy(r){if(ny(r))return(async()=>{for await(let e of r);})();for(let e of r);}var zc=oy;function sy(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 Vh=sy;function iy(r){return r[Symbol.asyncIterator]!=null}function ay(r,e){let t=0;if(iy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Vh(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 await(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 Dr=ay;function cy(r){return r[Symbol.asyncIterator]!=null}function ly(r,e){return cy(r)?async function*(){yield*(await ao(r)).sort(e)}():function*(){yield*ao(r).sort(e)}()}var Yc=ly;function uy(r){return r[Symbol.asyncIterator]!=null}function fy(r,e){return uy(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 Wc=fy;var Js=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 zc(this.putMany(e,n)),e=[],await zc(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=Dr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Dr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yc(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Dr(n,()=>o++>=s)}return e.limit!=null&&(n=Wc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Dr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Dr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yc(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Dr(n,()=>s++>=o)}return e.limit!=null&&(n=Wc(n,e.limit)),n}};var $h=Ht(jc(),1);function qh(r){return r=r??new Error("Not Found"),(0,$h.default)(r,"ERR_NOT_FOUND")}var ei=class extends Js{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw qh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new kr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new kr(e)}};function Gh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var py=r=>r;function Xc(r,e){let t=r.getPeerId();return t!=null&&we(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var ti=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??py,this._updatePeerStoreAddresses=Gh(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>re(t))).map(t=>t.getPeerId()===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",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){e=Xc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Xc(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=Xc(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>re(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Zc=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=Ms())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Kl(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")}},my=["metrics","connectionProtector","dns"],gy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function zh(r={}){let e=new Zc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!gy.includes(o)){let i=e.components[o];if(i==null&&!my.includes(o))throw new y(`${o} not set`,"ERR_SERVICE_MISSING");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}})}var Wh=Ht(Yh(),1),yy=["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"],wy=yy.map(r=>new Wh.Netmask(r));function by(r){for(let e of wy)if(e.contains(r))return!0;return!1}function Ey(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function ri(r){return yn(r)?by(r):wn(r)?Ey(r):void 0}function jh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ri(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var xy=r=>r.toString().split("/").slice(1),po=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),W=r=>({match:e=>po(t=>t===r).match(e),pattern:r}),si=()=>({match:r=>po(e=>typeof e=="string").match(r),pattern:"{string}"}),ii=()=>({match:r=>po(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Be=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ne.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ni=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{pa.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ze=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=xy(o);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{matches:t,exactMatch:n}}var Jc=Q(W("dns4"),si()),el=Q(W("dns6"),si()),tl=Q(W("dnsaddr"),si()),Xh=Q(W("dns"),si()),NR=fe(Jc),LR=fe(el),kR=fe(tl),DR=fe(Ze(Xh,tl,Jc,el)),Zh=Q(W("ip4"),po(yn)),Qh=Q(W("ip6"),po(wn)),Jh=Ze(Zh,Qh),xt=Ze(Jh,Xh,Jc,el,tl),PR=fe(xt),OR=fe(Zh),UR=fe(Qh),MR=fe(Jh),ai=Q(xt,W("tcp"),ii()),mo=Q(xt,W("udp"),ii()),vy=Ze(ai,mo),FR=fe(ai),VR=fe(mo),rl=Q(mo,W("quic")),ci=Q(mo,W("quic-v1")),Ay=Ze(rl,ci),KR=fe(rl),HR=fe(ci),Qc=Ze(xt,ai,mo,rl,ci),ed=Ze(Q(Qc,W("ws"),Te(Be()))),$R=fe(ed),td=Ze(Q(Qc,W("wss"),Te(Be())),Q(Qc,W("tls"),W("ws"),Te(Be()))),qR=fe(td),rd=Q(vy,W("webrtc-direct"),ni(),Te(ni()),Te(Be())),GR=fe(rd),nd=Q(ci,W("webtransport"),Te(ni()),Te(ni()),Te(Be())),zR=fe(nd),oi=Ze(ed,td,Q(ai,Te(Be())),Q(Ay,Te(Be())),Q(xt,Te(Be())),rd,nd,Be()),YR=fe(oi),Ry=Q(oi,W("p2p-circuit"),Be()),go=fe(Ry),_y=Ze(Q(oi,W("p2p-circuit"),W("webrtc"),Be()),Q(oi,W("webrtc"),Te(Be())),W("webrtc")),WR=fe(_y),Sy=Ze(Q(xt,W("tcp"),ii(),W("http"),Te(Be())),Q(xt,W("http"),Te(Be()))),jR=fe(Sy),Iy=Ze(Q(xt,W("tcp"),Ze(Q(W("443"),W("http")),Q(ii(),W("https"))),Te(Be())),Q(xt,W("tls"),W("http"),Te(Be())),Q(xt,W("https"),Te(Be()))),XR=fe(Iy);function nl(r){try{let{address:e}=r.nodeAddress();return!!ri(e)}catch{return!0}}function By(r,e){let t=nl(r.multiaddr),n=nl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ty(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Cy(r,e){let t=go.exactMatch(r.multiaddr),n=go.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _n(r,e){let t=By(r,e);if(t!==0)return t;let n=Cy(r,e);return n!==0?n:Ty(r,e)}var hr=class extends Event{constructor(e,t){super(e),this.detail=t}};function li(r){let e=[Qe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var ol=60;function ui(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:Qe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Qe[e.type],TTL:e.TTL??e.ttl??ol,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var Ny=4;function sl(r,e={}){let t=new lr({concurrency:e.queryConcurrency??Ny});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),li(o.types).forEach(a=>{s.append("type",Qe[a])}),o.onProgress?.(new hr("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=ui(await a.json());return o.onProgress?.(new hr("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function od(){return[sl("https://cloudflare-dns.com/dns-query"),sl("https://dns.google/resolve")]}var ad=Ht(id(),1);var il=class{lru;constructor(e){this.lru=(0,ad.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 ui({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:Qe[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??ol)*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 cd(r){return new il(r)}var Ly=1e3,fi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=cd(e.cacheSize??Ly),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["."]=od())}async query(e,t={}){let n=li(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new hr("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new hr("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Qe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Qe||(Qe={}));function ld(r={}){return new fi(r)}var ky=32,{code:Dy}=X("dnsaddr"),Pr=async function(e,t={}){let n=t.maxRecursiveDepth??ky;if(n===0)throw new y("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===Dy)??[],i=await(t?.dns??ld()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Qe.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=re(f);if(f.startsWith("/dnsaddr")){let h=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(g=>g.toString()))}else c.push(l.toString())}return c};var wd=Ht(yd(),1),pi=wd.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var B;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(B||(B={}));var Vy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Pr},addressSorter:_n},transportManager:{faultTolerance:$t.FATAL_ALL}};async function bd(r){let e=pi(Vy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new y(Vt.ERR_PROTECTOR_REQUIRED,B.ERR_PROTECTOR_REQUIRED);if(!(await dn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new y("Private key doesn't match peer id",B.ERR_INVALID_KEY);return e}var Ed=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Ky=new WeakMap;function Hy({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Ed());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Ed())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((h,g)=>{i=()=>{f(),h(n)},a=g,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Ky.set(l,()=>{c(s),s=null,i()}),l}}var $y=Hy(),xd=$y;var mi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new cl}async 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 y("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await xd(a)}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)}},cl=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 gi(r){if(Ro(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:we(t),r.forEach(n=>{if(!cr(n))throw new y("Invalid Multiaddr",B.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}else{let s=we(o);if(e==null||!e.equals(s))throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var yi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Bn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new yi(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 yi(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 ll=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function wi(r={}){return qy(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 qy(r,e){e=e??{};let t=e.onEnd,n=new Bn,o,s,i,a=ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,w)=>{s=x=>{s=null,n.push(x);try{m(r(n))}catch(b){w(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ce()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Bn,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},h=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),g=()=>(n=new Bn,h(),{done:!0}),d=m=>(h(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:d,push:l,end:h,get readableLength(){return n.size},onEmpty:async m=>{let w=m?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,b;w!=null&&(x=new Promise((A,v)=>{b=()=>{v(new ll)},w.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&w!=null&&w?.removeEventListener("abort",b)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return p.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},o}var ul=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Tn(r,e,t,n){let o=new ul(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(h){a(),i(h);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var bi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function dr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new bi(t?.errorMessage,t?.errorCode));let n,o=new bi(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ei=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=ce(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new qt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Gy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Gy(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ue(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new qt),this.cleanup())}async join(e={}){let t=new Ei(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dr(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)})}};var Cn=class extends At{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let 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){t?.signal?.throwIfAborted();let n=new xi(e,t),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("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new qt)}),this.clear()}async onEmpty(e){this.size!==0&&await Tn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Tn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Tn(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=wi({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)},i=()=>{n()},a=()=>{n(new y("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var vi=class extends Cn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ai="last-dial-failure";var Ri=5,_i=100,Si=50,Ii=1e3*60*7;var Or={minConnections:Ri,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Ii,autoDialDiscoveredPeersDebounce:10},Bi=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Or.minConnections,this.autoDialPriority=t.autoDialPriority??Or.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Or.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Or.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Or.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Or.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new vi({concurrency:t.autoDialConcurrency??Or.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ft(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,h=i.get(f.id)??0;return l>h?-1:l<h?1:0}).filter(u=>{let f=u.metadata.get(Ai);if(f==null)return!0;let l=parseInt(K(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Yy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function vd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Yy;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Ad={maxConnections:_i,allow:[]},Ti=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ad.maxConnections,this.allow=t.allow??Ad.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Xe;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await vd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}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 Ci=class extends Cn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function yo(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.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}async function Rd(r,e){let t=!1;for(let o of En.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var wo={addressSorter:_n,maxParallelDials:Si,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Pr}},Ni=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??wo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??wo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??wo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??wo.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ue(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))En.set(n,o);this.queue=new Ci({concurrency:t.maxParallelDials??wo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ue(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=gi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new y("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let h of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new y("Peer had more than maxPeerAddrsToDial",B.ERR_TOO_MANY_ADDRESSES);f++;try{let g=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),g}catch(g){if(this.log.error("dial failed to %a",h.multiaddr,g),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ai]:D(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new y(g.message,So);l.push(g)}}throw l.length===1?l[0]:new _o(l,"All multiaddr dials failed",B.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??wl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=yo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ue(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:re(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new y("Tried to dial self",B.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new y("The dial request is blocked by gater.allowDialPeer",B.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(l){if(l.code!==B.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...l.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(l){l.code!==B.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let h=await Rd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(g=>({multiaddr:g,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let h=l.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let l of i){let h=l.multiaddr.toString(),g=a.get(h);if(g!=null){g.isCertified=g.isCertified||l.isCertified||!1;continue}a.set(h,l)}let c=[...a.values()];if(c.length===0)throw new y("The dial request has no valid addresses",B.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new y("The connection gater denied all addresses in the dial request",B.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}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.runOnTransientConnection===!1?n.find(o=>!go.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var wl=50,Kt={minConnections:Ri,maxConnections:_i,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Ii,autoDialDiscoveredPeersDebounce:10},Li=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kt.maxConnections;let n=t.minConnections??Kt.minConnections;if(this.maxConnections<n)throw new y("Connection Manager maxConnections must be greater than minConnections",B.ERR_INVALID_PARAMETERS);this.connections=new Xe,this.started=!1,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.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>re(o)),this.deny=(t.deny??[]).map(o=>re(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new mi({points:t.inboundConnectionThreshold??Kt.inboundConnectionThreshold,duration:1}),this.autoDial=new Bi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Kt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Kt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Kt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Kt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??Kt.autoDialMaxQueueLength}),this.connectionPruner=new Ti({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ni(e,{addressSorter:t.addressSorter??_n,maxParallelDials:t.maxParallelDials??Si,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Pr},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;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.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Vl)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}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.isStarted())throw new y("Not started",B.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=gi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??wl}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};function Xy(r){return r[Symbol.asyncIterator]!=null}function Zy(...r){let e=[];for(let t of r)Xy(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=wi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var bo=Zy;var ki=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}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 y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of bo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new y(Vt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new y(Vt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Di=globalThis.CustomEvent??Event;async function*bl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ce(),a=ce(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=ce(),await i.promise),f)break;let p={done:!1};s.push(p),d().then(m=>{p.done=!0,p.ok=!0,p.value=m,o.dispatchEvent(new Di("task-complete"))},m=>{p.done=!0,p.err=m,o.dispatchEvent(new Di("task-complete"))})}c=!0,o.dispatchEvent(new Di("task-complete"))}catch(d){u=d,o.dispatchEvent(new Di("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*h(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*g(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let p=s[d];if(s.splice(d,1),d--,p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}for(;;){if(l()||(a=ce(),await a.promise),u!=null)throw u;if(n?yield*h():yield*g(),c&&s.length===0)break}}var Pi=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??[]}async findPeer(e,t){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new y("Should not try to find self",B.ERR_FIND_SELF);let n=this,o=bo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new y(Vt.NOT_FOUND,B.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of bl(async function*(){let i=bo(...n.routers.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",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Oi=class extends At{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,ue(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,ue(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=yo([this.shutdownController.signal,e?.signal]);ue(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ce(),yield(await Tn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ue(1/0,this.walkController.signal);let e=yo([this.walkController.signal,this.shutdownController.signal]);ue(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(yt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await dr(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var El=32,xl=64,Ui=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,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)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new y(`No handler registered for protocol ${e}`,B.ERR_NO_HANDLER_FOR_PROTOCOL);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))throw new y(`Handler already registered for protocol ${e}`,B.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=pi.bind({ignoreUndefined:!0})({maxInboundStreams:El,maxOutboundStreams:xl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new y("invalid topology",B.ERR_INVALID_PARAMETERS);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))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==B.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var vl=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 _d(r){let{name:e,metrics:t}=r,n;return t!=null?n=new vl({name:e,metrics:t}):n=new Map,n}var Mi=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=new Map,this.listeners=_d({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??$t.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new y("Transport must have a valid tag",B.ERR_INVALID_KEY);if(this.transports.has(t))throw new y(`There is already a transport with the tag ${t}`,B.ERR_DUPLICATE_TRANSPORT);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 y(`No transport available for address ${String(e)}`,B.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=B.ERR_TRANSPORT_DIAL_FAILED),o}}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 y("Not started",B.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let h=l.findIndex(g=>g===f);l.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==$t.NO_FATAL)throw new y(`Transport (${n}) could not listen on any available address`,B.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===$t.FATAL_ALL)throw new y(n,B.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Ce="/multistream/1.0.0";var Al=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ce(),this.haveNext=ce()}[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=ce(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),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 new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ce(),await dr(this.readNext.promise,t?.signal,t)}};function Sd(){return new Al}var Fi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Rl=class extends Fi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Id(r,e){let t=Sd();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new be;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Rl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:h}=await Promise.race([n.next(),u]);return l===!0?new be:h}for(;o.byteLength<i;){let{value:l,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new Fi("unexpected end of input","ERR_UNEXPECTED_EOF");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Vi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function Eo(r,e={}){let t=Id(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??De;return{read:async i=>{let a=-1,c=new be;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Vi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Vi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new be(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new be(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Qy=D(`
8
- `);async function Ur(r,e,t){await r.write(e,t)}async function Bd(r,e,t){await r.writeV(e,t)}async function Jy(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Qy[0])throw e.log.error("Invalid mss message - missing newline",t),new y("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function pr(r,e){let t=await Jy(r,e);return K(t.subarray())}async function xo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return ew(r,e[0],t);let n=Eo(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Ce,o);let s=D(`${Ce}
6
+ `)}`:`${t} :`}};ef=rr;I.Constructed=ef;rr.NAME="CONSTRUCTED";var rs=class extends Oe{fromBER(e,t,n){return t}toBER(e){return lt}};rs.override="EndOfContentValueBlock";var tf,ns=class extends Ie{constructor(e={}){super(e,rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};tf=ns;I.EndOfContent=tf;ns.NAME=Gn;var rf,nr=class extends Ie{constructor(e={}){super(e,Oe),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}`}};rf=nr;I.Null=rf;nr.NAME="NULL";var os=class extends Ut(Oe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=H.BufferSourceConverter.toUint8Array(e);return Ot(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,rc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};os.NAME="BooleanValueBlock";var nf,ss=class extends Ie{constructor(e={}){super(e,os),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};nf=ss;I.Boolean=nf;ss.NAME="BOOLEAN";var is=class extends Ut(wt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Xu)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?wt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};is.NAME="OctetStringValueBlock";var of,Dt=class r extends Ie{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},is),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ds(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?rr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return H.BufferSourceConverter.concat(e)}};of=Dt;I.OctetString=of;Dt.NAME=Xu;var as=class extends Ut(wt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Zu)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=H.BufferSourceConverter.toUint8Array(e);if(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ds(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return wt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return lt;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}}};as.NAME="BitStringValueBlock";var sf,on=class extends Ie{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},as),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};sf=on;I.BitString=sf;on.NAME=Zu;var af;function Dg(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,u=0,f=c<i?i:c,l=0;for(let h=f;h>=0;h--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=jo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=jo(t,s)),s}function ju(r){if(r>=$n.length)for(let e=$n.length;e<=r;e++){let t=new Uint8Array([0]),n=$n[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=jo(t,n)),$n.push(n)}return $n[r]}function Pg(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,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var zn=class extends Ut(Oe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=rc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(zu(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?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 u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=Pg(ju(n),t),i="-";break;default:t=Dg(t,ju(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Wu.charAt(t[c]));return a===!1&&(i+=Wu.charAt(0)),i}};af=zn;zn.NAME="IntegerValueBlock";Object.defineProperty(af.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var cf,me=class r extends Ie{constructor(e={}){super(e,zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Xo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Xo();let t=BigInt(e),n=new qn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(H.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${H.Convert.ToHex(a)}`)+t,f=H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};cf=me;I.Integer=cf;me.NAME="INTEGER";var lf,cs=class extends me{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};lf=cs;I.Enumerated=lf;cs.NAME="ENUMERATED";var Yn=class extends Ut(Oe){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=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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));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?(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=_r(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Xo();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=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;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=H.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}}};Yn.NAME="sidBlock";var ls=class extends Oe{constructor({value:e=sn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Yn;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,lt;t.push(o)}return nc(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 Yn;if(o>Number.MAX_SAFE_INTEGER){Xo();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}};ls.NAME="ObjectIdentifierValueBlock";var uf,ct=class extends Ie{constructor(e={}){super(e,ls),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};uf=ct;I.ObjectIdentifier=uf;ct.NAME="OBJECT IDENTIFIER";var Wn=class extends Ut(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=H.BufferSourceConverter.toUint8Array(e);if(!Ot(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));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?(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=_r(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=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;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=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Wn.NAME="relativeSidBlock";var us=class extends Oe{constructor({value:e=sn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;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,lt;n.push(s)}return nc(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 Wn;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}};us.NAME="RelativeObjectIdentifierValueBlock";var ff,fs=class extends Ie{constructor(e={}){super(e,us),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};ff=fs;I.RelativeObjectIdentifier=ff;fs.NAME="RelativeObjectIdentifier";var hf,ve=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};hf=ve;I.Sequence=hf;ve.NAME="SEQUENCE";var df,hs=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};df=hs;I.Set=df;hs.NAME="SET";var ds=class extends Ut(Oe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=sn}toJSON(){return{...super.toJSON(),value:this.value}}};ds.NAME="StringValueBlock";var ps=class extends ds{};ps.NAME="SimpleStringValueBlock";var He=class extends Jo{constructor({...e}={}){super(e,ps)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.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}};He.NAME="SIMPLE STRING";var ms=class extends He{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ms.NAME="Utf8StringValueBlock";var pf,Pt=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};pf=Pt;I.Utf8String=pf;Pt.NAME="UTF8String";var gs=class extends He{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};gs.NAME="BmpStringValueBlock";var mf,ys=class extends gs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};mf=ys;I.BmpString=mf;ys.NAME="BMPString";var ws=class extends He{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=tr(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}};ws.NAME="UniversalStringValueBlock";var gf,bs=class extends ws{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};gf=bs;I.UniversalString=gf;bs.NAME="UniversalString";var yf,Es=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};yf=Es;I.NumericString=yf;Es.NAME="NumericString";var wf,xs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};wf=xs;I.PrintableString=wf;xs.NAME="PrintableString";var bf,vs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};bf=vs;I.TeletexString=bf;vs.NAME="TeletexString";var Ef,As=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Ef=As;I.VideotexString=Ef;As.NAME="VideotexString";var xf,Rs=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};xf=Rs;I.IA5String=xf;Rs.NAME="IA5String";var vf,_s=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};vf=_s;I.GraphicString=vf;_s.NAME="GraphicString";var Af,jn=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Af=jn;I.VisibleString=Af;jn.NAME="VisibleString";var Rf,Ss=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Rf=Ss;I.GeneralString=Rf;Ss.NAME="GeneralString";var _f,Is=class extends He{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};_f=Is;I.CharacterString=_f;Is.NAME="CharacterString";var Sf,Xn=class extends jn{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,H.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]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(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}}};Sf=Xn;I.UTCTime=Sf;Xn.NAME="UTCTime";var If,Bs=class extends Xn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.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 l=1,h=n.indexOf("+"),g="";if(h===-1&&(h=n.indexOf("-"),l=-1),h!==-1){if(g=n.substring(h+1),n=n.substring(0,h),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(g.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,g.length===4){if(d=parseInt(g.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-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,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};If=Bs;I.GeneralizedTime=If;Bs.NAME="GeneralizedTime";var Bf,Ts=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Bf=Ts;I.DATE=Bf;Ts.NAME="DATE";var Tf,Cs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Tf=Cs;I.TimeOfDay=Tf;Cs.NAME="TimeOfDay";var Cf,Ns=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Cf=Ns;I.DateTime=Cf;Ns.NAME="DateTime";var Nf,Ls=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Nf=Ls;I.Duration=Nf;Ls.NAME="Duration";var Lf,ks=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Lf=ks;I.TIME=Lf;ks.NAME="TIME";function Ug(r){let{result:e}=an(r),t=e.valueBlock.value;return{n:K(bt(t[1].toBigInt()),"base64url"),e:K(bt(t[2].toBigInt()),"base64url"),d:K(bt(t[3].toBigInt()),"base64url"),p:K(bt(t[4].toBigInt()),"base64url"),q:K(bt(t[5].toBigInt()),"base64url"),dp:K(bt(t[6].toBigInt()),"base64url"),dq:K(bt(t[7].toBigInt()),"base64url"),qi:K(bt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Mg(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 y("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new ve({value:[new me({value:0}),me.fromBigInt(Et(D(r.n,"base64url"))),me.fromBigInt(Et(D(r.e,"base64url"))),me.fromBigInt(Et(D(r.d,"base64url"))),me.fromBigInt(Et(D(r.p,"base64url"))),me.fromBigInt(Et(D(r.q,"base64url"))),me.fromBigInt(Et(D(r.dp,"base64url"))),me.fromBigInt(Et(D(r.dq,"base64url"))),me.fromBigInt(Et(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Fg(r){let{result:e}=an(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:K(bt(t[0].toBigInt()),"base64url"),e:K(bt(t[1].toBigInt()),"base64url")}}function Vg(r){if(r.n==null||r.e==null)throw new y("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new ve({value:[new ve({value:[new ct({value:"1.2.840.113549.1.1.1"}),new nr]}),new on({valueHex:new ve({value:[me.fromBigInt(Et(D(r.n,"base64url"))),me.fromBigInt(Et(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function Et(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var Kg=16,sc=32,ic=1e4;async function Hg(r,e){let t=Me.get(),o=new ve({value:[new me({value:0}),new ve({value:[new ct({value:"1.2.840.113549.1.1.1"}),new nr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=yt(Kg),a=await ec(Xr,e,i,{c:ic,dkLen:sc}),c=yt(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new ve({value:[new Dt({valueHex:i}),new me({value:ic}),new me({value:sc}),new ve({value:[new ct({value:"1.2.840.113549.2.11"}),new nr]})]}),h=new ve({value:[new ct({value:"1.2.840.113549.1.5.13"}),new ve({value:[new ve({value:[new ct({value:"1.2.840.113549.1.5.12"}),l]}),new ve({value:[new ct({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new ve({value:[h,new Dt({valueHex:f})]}).toBER(),p=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...K(p,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
+ `)}async function $g(r,e){let t=Me.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=an(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=qg(s),l=await ec(Xr,e,a,{c,dkLen:u}),h=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),g=Zn(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,f)),{result:d}=an(g);n=kf(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=an(o);n=kf(s)}else throw new y("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return ac(n)}function qg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new y("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new y("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Zn(s.valueBlock.value[0].getValue()),a=ic,c=sc;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 y("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new y("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Zn(u.valueBlock.value[1].getValue());return{cipherText:Zn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function kf(r){return Zn(r.valueBlock.value[2].getValue())}function Zn(r){return new Uint8Array(r,0,r.byteLength)}async function Df(r){let e=await Me.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Uf(e);return{privateKey:t[0],publicKey:t[1]}}async function cc(r){let t=[await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Gg(r)],n=await Uf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Pf(r,e){let t=await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Me.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Of(r,e,t){let n=await Me.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Me.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Uf(r){if(r.privateKey==null||r.publicKey==null)throw new y("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Me.get().subtle.exportKey("jwk",r.privateKey),Me.get().subtle.exportKey("jwk",r.publicKey)])}async function Gg(r){return Me.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ps(r){if(r.kty!=="RSA")throw new y("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new y("invalid key modulus","ERR_INVALID_KEY_MODULUS");return D(r.n,"base64url").length*8}var Jn=8192,Qn=class{_key;constructor(e){this._key=e}verify(e,t){return Of(this._key,t,e)}marshal(){return or.jwkToPkix(this._key)}get bytes(){return mt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=_e.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},cn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return yt(16)}sign(e){return Pf(this._key,e)}get public(){if(this._publicKey==null)throw new y("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Qn(this._publicKey)}marshal(){return or.jwkToPkcs1(this._key)}get bytes(){return gt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=_e.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return or.exportToPem(this,e);if(t==="libp2p-key")return en(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function ac(r){let e=or.pkcs1ToJwk(r);if(Ps(e)>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await cc(e);return new cn(t.privateKey,t.publicKey)}function Yg(r){let e=or.pkixToJwk(r);if(Ps(e)>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Qn(e)}async function Wg(r){if(Ps(r)>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await cc(r);return new cn(e.privateKey,e.publicKey)}async function jg(r){if(r>Jn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Df(r);return new cn(e.privateKey,e.publicKey)}var pc={};xe(pc,{Secp256k1PrivateKey:()=>to,Secp256k1PublicKey:()=>eo,generateKeyPair:()=>c0,unmarshalSecp256k1PrivateKey:()=>i0,unmarshalSecp256k1PublicKey:()=>a0});var Xg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=new Uint32Array(64),uc=class extends jr{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[7]|0}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 l=0;l<16;l++,t+=4)ir[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=ir[l-15],g=ir[l-2],d=ot(h,7)^ot(h,18)^h>>>3,p=ot(g,17)^ot(g,19)^g>>>10;ir[l]=p+ir[l-7]+d+ir[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let h=ot(a,6)^ot(a,11)^ot(a,25),g=f+h+du(a,c,u)+Xg[l]+ir[l]|0,p=(ot(n,2)^ot(n,13)^ot(n,22))+pu(n,o,s)|0;f=u,u=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+p|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,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Mf=Lo(()=>new uc);function Zg(r){let e=Mn(r);pt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Qg,hexToBytes:Jg}=Po,Sr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Sr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Qg(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Sr,t=typeof r=="string"?Jg(r):r;Zr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Sr._parseInt(t.subarray(2)),{d:i,l:a}=Sr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Mt=BigInt(0),tt=BigInt(1),$x=BigInt(2),Ff=BigInt(3),qx=BigInt(4);function e0(r){let e=Zg(r),{Fp:t}=e,n=e.toBytes||((d,p,m)=>{let w=p.toAffine();return Tt(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(d=>{let p=d.subarray(1),m=t.fromBytes(p.subarray(0,t.BYTES)),w=t.fromBytes(p.subarray(t.BYTES,2*t.BYTES));return{x:m,y:w}});function s(d){let{a:p,b:m}=e,w=t.sqr(d),x=t.mul(w,d);return t.add(t.add(x,t.mul(d,p)),m)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Mt<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:p,nByteLength:m,wrapPrivateKey:w,n:x}=e;if(p&&typeof d!="bigint"){if(Zt(d)&&(d=It(d)),typeof d!="string"||!p.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(ae("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return w&&(b=Z(b,x)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,w){if(this.px=p,this.py=m,this.pz=w,p==null||!t.isValid(p))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(p){let{x:m,y:w}=p||{};if(!p||!t.isValid(m)||!t.isValid(w))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let x=b=>t.eql(b,t.ZERO);return x(m)&&x(w)?l.ZERO:new l(m,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=t.invertBatch(p.map(w=>w.pz));return p.map((w,x)=>w.toAffine(m[x])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(o(ae("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!t.isValid(p)||!t.isValid(m))throw new Error("bad point: x or y not FE");let w=t.sqr(m),x=s(p);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(t.isOdd)return!t.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.eql(t.mul(m,v),t.mul(b,x)),C=t.eql(t.mul(w,v),t.mul(A,x));return S&&C}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:p,b:m}=e,w=t.mul(m,Ff),{px:x,py:b,pz:A}=this,v=t.ZERO,S=t.ZERO,C=t.ZERO,N=t.mul(x,x),q=t.mul(b,b),G=t.mul(A,A),U=t.mul(x,b);return U=t.add(U,U),C=t.mul(x,A),C=t.add(C,C),v=t.mul(p,C),S=t.mul(w,G),S=t.add(v,S),v=t.sub(q,S),S=t.add(q,S),S=t.mul(v,S),v=t.mul(U,v),C=t.mul(w,C),G=t.mul(p,G),U=t.sub(N,G),U=t.mul(p,U),U=t.add(U,C),C=t.add(N,N),N=t.add(C,N),N=t.add(N,G),N=t.mul(N,U),S=t.add(S,N),G=t.mul(b,A),G=t.add(G,G),N=t.mul(G,U),v=t.sub(v,N),C=t.mul(G,q),C=t.add(C,C),C=t.add(C,C),new l(v,S,C)}add(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.ZERO,C=t.ZERO,N=t.ZERO,q=e.a,G=t.mul(e.b,Ff),U=t.mul(m,b),he=t.mul(w,A),le=t.mul(x,v),Qe=t.add(m,w),R=t.add(b,A);Qe=t.mul(Qe,R),R=t.add(U,he),Qe=t.sub(Qe,R),R=t.add(m,x);let L=t.add(b,v);return R=t.mul(R,L),L=t.add(U,le),R=t.sub(R,L),L=t.add(w,x),S=t.add(A,v),L=t.mul(L,S),S=t.add(he,le),L=t.sub(L,S),N=t.mul(q,R),S=t.mul(G,le),N=t.add(S,N),S=t.sub(he,N),N=t.add(he,N),C=t.mul(S,N),he=t.add(U,U),he=t.add(he,U),le=t.mul(q,le),R=t.mul(G,R),he=t.add(he,le),le=t.sub(U,le),le=t.mul(q,le),R=t.add(R,le),U=t.mul(he,R),C=t.add(C,U),U=t.mul(L,R),S=t.mul(Qe,S),S=t.sub(S,U),U=t.mul(Qe,he),N=t.mul(L,N),N=t.add(N,U),new l(S,C,N)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return g.wNAFCached(this,u,p,m=>{let w=t.invertBatch(m.map(x=>x.pz));return m.map((x,b)=>x.toAffine(w[b])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===Mt)return m;if(a(p),p===tt)return this;let{endo:w}=e;if(!w)return g.unsafeLadder(this,p);let{k1neg:x,k1:b,k2neg:A,k2:v}=w.splitScalar(p),S=m,C=m,N=this;for(;b>Mt||v>Mt;)b&tt&&(S=S.add(N)),v&tt&&(C=C.add(N)),N=N.double(),b>>=tt,v>>=tt;return x&&(S=S.negate()),A&&(C=C.negate()),C=new l(t.mul(C.px,w.beta),C.py,C.pz),S.add(C)}multiply(p){a(p);let m=p,w,x,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:S,k2:C}=b.splitScalar(m),{p:N,f:q}=this.wNAF(v),{p:G,f:U}=this.wNAF(C);N=g.constTimeNegate(A,N),G=g.constTimeNegate(S,G),G=new l(t.mul(G.px,b.beta),G.py,G.pz),w=N.add(G),x=q.add(U)}else{let{p:A,f:v}=this.wNAF(m);w=A,x=v}return l.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(p,m,w){let x=l.BASE,b=(v,S)=>S===Mt||S===tt||!v.equals(x)?v.multiplyUnsafe(S):v.multiply(S),A=b(this,m).add(b(p,w));return A.is0()?void 0:A}toAffine(p){let{px:m,py:w,pz:x}=this,b=this.is0();p==null&&(p=b?t.ONE:t.inv(x));let A=t.mul(m,p),v=t.mul(w,p),S=t.mul(x,p);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=e;if(p===tt)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=e;return p===tt?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return It(this.toRawBytes(p))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,g=Mo(l,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function t0(r){let e=Mn(r);return pt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Vf(r){let e=t0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(R){return Mt<R&&R<t.ORDER}function a(R){return Z(R,n)}function c(R){return Oo(R,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=e0({...e,toBytes(R,L,M){let _=L.toAffine(),E=t.toBytes(_.x),T=Tt;return M?T(Uint8Array.from([L.hasEvenY()?2:3]),E):T(Uint8Array.from([4]),E,t.toBytes(_.y))},fromBytes(R){let L=R.length,M=R[0],_=R.subarray(1);if(L===o&&(M===2||M===3)){let E=Bt(_);if(!i(E))throw new Error("Point is not on curve");let T=l(E),k;try{k=t.sqrt(T)}catch(V){let Y=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+Y)}let P=(k&tt)===tt;return(M&1)===1!==P&&(k=t.neg(k)),{x:E,y:k}}else if(L===s&&M===4){let E=t.fromBytes(_.subarray(0,t.BYTES)),T=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:E,y:T}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),g=R=>It(Jt(R,e.nByteLength));function d(R){let L=n>>tt;return R>L}function p(R){return d(R)?a(-R):R}let m=(R,L,M)=>Bt(R.slice(L,M));class w{constructor(L,M,_){this.r=L,this.s=M,this.recovery=_,this.assertValidity()}static fromCompact(L){let M=e.nByteLength;return L=ae("compactSignature",L,M*2),new w(m(L,0,M),m(L,M,2*M))}static fromDER(L){let{r:M,s:_}=Sr.toSig(ae("DER",L));return new w(M,_)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:_,recovery:E}=this,T=C(ae("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let k=E===2||E===3?M+e.n:M;if(k>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=E&1?"03":"02",F=u.fromHex(P+g(k)),V=c(k),Y=a(-T*V),$=a(_*V),z=u.BASE.multiplyAndAddUnsafe(F,Y,$);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return wr(this.toDERHex())}toDERHex(){return Sr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return wr(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let x={isValidPrivateKey(R){try{return f(R),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let R=Ba(e.n);return _u(e.randomBytes(R),e.n)},precompute(R=8,L=u.BASE){return L._setWindowSize(R),L.multiply(BigInt(3)),L}};function b(R,L=!0){return u.fromPrivateKey(R).toRawBytes(L)}function A(R){let L=Zt(R),M=typeof R=="string",_=(L||M)&&R.length;return L?_===o||_===s:M?_===2*o||_===2*s:R instanceof u}function v(R,L,M=!0){if(A(R))throw new Error("first arg must be private key");if(!A(L))throw new Error("second arg must be public key");return u.fromHex(L).multiply(f(R)).toRawBytes(M)}let S=e.bits2int||function(R){let L=Bt(R),M=R.length*8-e.nBitLength;return M>0?L>>BigInt(M):L},C=e.bits2int_modN||function(R){return a(S(R))},N=Un(e.nBitLength);function q(R){if(typeof R!="bigint")throw new Error("bigint expected");if(!(Mt<=R&&R<N))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Jt(R,e.nByteLength)}function G(R,L,M=U){if(["recovered","canonical"].some(oe=>oe in M))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:E}=e,{lowS:T,prehash:k,extraEntropy:P}=M;T==null&&(T=!0),R=ae("msgHash",R),k&&(R=ae("prehashed msgHash",_(R)));let F=C(R),V=f(L),Y=[q(V),q(F)];if(P!=null&&P!==!1){let oe=P===!0?E(t.BYTES):P;Y.push(ae("extraEntropy",oe))}let $=Tt(...Y),z=F;function de(oe){let Ae=S(oe);if(!h(Ae))return;let Re=c(Ae),ge=u.BASE.multiply(Ae).toAffine(),Ne=a(ge.x);if(Ne===Mt)return;let vt=a(Re*a(z+Ne*V));if(vt===Mt)return;let mr=(ge.x===Ne?0:2)|Number(ge.y&tt),Ln=vt;return T&&d(vt)&&(Ln=p(vt),mr^=1),new w(Ne,Ln,mr)}return{seed:$,k2sig:de}}let U={lowS:e.lowS,prehash:!1},he={lowS:e.lowS,prehash:!1};function le(R,L,M=U){let{seed:_,k2sig:E}=G(R,L,M),T=e;return Ra(T.hash.outputLen,T.nByteLength,T.hmac)(_,E)}u.BASE._setWindowSize(8);function Qe(R,L,M,_=he){let E=R;if(L=ae("msgHash",L),M=ae("publicKey",M),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:T,prehash:k}=_,P,F;try{if(typeof E=="string"||Zt(E))try{P=w.fromDER(E)}catch(ge){if(!(ge instanceof Sr.Err))throw ge;P=w.fromCompact(E)}else if(typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint"){let{r:ge,s:Ne}=E;P=new w(ge,Ne)}else throw new Error("PARSE");F=u.fromHex(M)}catch(ge){if(ge.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&P.hasHighS())return!1;k&&(L=e.hash(L));let{r:V,s:Y}=P,$=C(L),z=c(Y),de=a($*z),oe=a(V*z),Ae=u.BASE.multiplyAndAddUnsafe(F,de,oe)?.toAffine();return Ae?a(Ae.x)===V:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:le,verify:Qe,ProjectivePoint:u,Signature:w,utils:x}}function r0(r){return{hash:r,hmac:(e,...t)=>Hn(r,e,No(...t)),randomBytes:Wr}}function Kf(r,e){let t=n=>Vf({...r,...r0(n)});return Object.freeze({...t(e),create:t})}var qf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Hf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),n0=BigInt(1),fc=BigInt(2),$f=(r,e)=>(r+e/fc)/e;function o0(r){let e=qf,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ee(f,t,e)*f%e,h=ee(l,t,e)*f%e,g=ee(h,fc,e)*u%e,d=ee(g,o,e)*g%e,p=ee(d,s,e)*d%e,m=ee(p,a,e)*p%e,w=ee(m,c,e)*m%e,x=ee(w,a,e)*p%e,b=ee(x,t,e)*f%e,A=ee(b,i,e)*d%e,v=ee(A,n,e)*u%e,S=ee(v,fc,e);if(!hc.eql(hc.sqr(S),r))throw new Error("Cannot find square root");return S}var hc=Uo(qf,void 0,void 0,{sqrt:o0}),ut=Kf({a:BigInt(0),b:BigInt(7),Fp:hc,n:Hf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Hf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-n0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=$f(s*r,e),c=$f(-n*r,e),u=Z(r-a*t-c*o,e),f=Z(-a*n-c*s,e),l=u>i,h=f>i;if(l&&(u=e-u),h&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},Mf),Jx=BigInt(0);var ev=ut.ProjectivePoint;function Gf(){return ut.utils.randomPrivateKey()}function zf(r,e){let t=_e.digest(e instanceof Uint8Array?e:e.subarray());if(Je(t))return t.then(({digest:n})=>ut.sign(n,r).toDERRawBytes()).catch(n=>{throw new y(String(n),"ERR_INVALID_INPUT")});try{return ut.sign(t.digest,r).toDERRawBytes()}catch(n){throw new y(String(n),"ERR_INVALID_INPUT")}}function Yf(r,e,t){let n=_e.digest(t instanceof Uint8Array?t:t.subarray());if(Je(n))return n.then(({digest:o})=>ut.verify(e,o,r)).catch(o=>{throw new y(String(o),"ERR_INVALID_INPUT")});try{return ut.verify(e,n.digest,r)}catch(o){throw new y(String(o),"ERR_INVALID_INPUT")}}function Wf(r){return ut.ProjectivePoint.fromHex(r).toRawBytes(!0)}function jf(r){try{ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}function dc(r){try{ut.ProjectivePoint.fromHex(r)}catch(e){throw new y(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Xf(r){try{return ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}var eo=class{_key;constructor(e){dc(e),this._key=e}verify(e,t){return Yf(this._key,t,e)}marshal(){return Wf(this._key)}get bytes(){return mt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=_e.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}},to=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Xf(e),jf(this._key),dc(this._publicKey)}sign(e){return zf(this._key,e)}get public(){return new eo(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=_e.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return en(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function i0(r){return new to(r)}function a0(r){return new eo(r)}async function c0(){let r=Gf();return new to(r)}var ar={rsa:lc,ed25519:Ja,secp256k1:pc};function mc(r){let e=Object.keys(ar).join(" / ");return new y(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function gc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ar[r];throw mc(r)}async function Zf(r,e){return gc(r).generateKeyPair(e??2048)}function ro(r){let e=mt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return ar.rsa.unmarshalRsaPublicKey(t);case te.Ed25519:return ar.ed25519.unmarshalEd25519PublicKey(t);case te.Secp256k1:return ar.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw mc(e.Type??"unknown")}}function Qf(r,e){return e=(e??"rsa").toLowerCase(),gc(e),r.bytes}async function no(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return ar.rsa.unmarshalRsaPrivateKey(t);case te.Ed25519:return ar.ed25519.unmarshalEd25519PrivateKey(t);case te.Secp256k1:return ar.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw mc(e.Type??"RSA")}}function Jf(r,e){return e=(e??"rsa").toLowerCase(),gc(e),r.bytes}var je=Ht(oh(),1);je.default.formatters.b=r=>r==null?"undefined":ne.baseEncode(r);je.default.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);je.default.formatters.m=r=>r==null?"undefined":Pn.baseEncode(r);je.default.formatters.p=r=>r==null?"undefined":r.toString();je.default.formatters.c=r=>r==null?"undefined":r.toString();je.default.formatters.k=r=>r==null?"undefined":r.toString();je.default.formatters.a=r=>r==null?"undefined":r.toString();function x0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ms(){return{forComponent(r){return v0(r)}}}function v0(r){let e=x0(`${r}:trace`);return je.default.enabled(`${r}:trace`)&&je.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,je.default)(`${r}:trace`)),Object.assign((0,je.default)(r),{error:(0,je.default)(`${r}:error`),trace:e})}var A0=Symbol.for("nodejs.util.inspect.custom"),sh=Object.values(Yt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Yt.identity.decoder),ih=114,yc=36,wc=37,oo=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Yi]=!0;toString(){return this.string==null&&(this.string=ne.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return nt.createV1(ih,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return we(e).equals(this);if(e?.multihash?.bytes!=null)return ie(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[A0](){return`PeerId(${this.toString()})`}},Br=class extends oo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends oo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Cr=class extends oo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function ah(r){if(r.type==="RSA")return new Br(r);if(r.type==="Ed25519")return new Tr(r);if(r.type==="secp256k1")return new Cr(r);throw new y("Not a PeerId","ERR_INVALID_PARAMETERS")}function we(r,e){if(e=e??sh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=gr(ne.decode(`z${r}`));return r.startsWith("12D")?new Tr({multihash:t}):r.startsWith("16U")?new Cr({multihash:t}):new Br({multihash:t})}return hn(sh.decode(r))}function hn(r){try{let e=gr(r);if(e.code===zt.code){if(e.digest.length===yc)return new Tr({multihash:e});if(e.digest.length===wc)return new Cr({multihash:e})}if(e.code===_e.code)return new Br({multihash:e})}catch{return R0(nt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function R0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==ih)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===_e.code)return new Br({multihash:r.multihash});if(e.code===zt.code){if(e.digest.length===yc)return new Tr({multihash:r.multihash});if(e.digest.length===wc)return new Cr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function dn(r,e){return r.length===yc?new Tr({multihash:dt(zt.code,r),privateKey:e}):r.length===wc?new Cr({multihash:dt(zt.code,r),privateKey:e}):new Br({multihash:await _e.digest(r),publicKey:r,privateKey:e})}function pn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return pn(this.map.entries(),e=>[we(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,we(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return pn(this.map.keys(),e=>we(e))}values(){return this.map.values()}get size(){return this.map.size}};var ft=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 pn(this.set.entries(),e=>{let t=we(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=we(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pn(this.set.values(),e=>we(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var lh=Symbol.for("@achingbrain/uint8arraylist");function ch(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 Fs(r){return!!r?.[lh]}var be=class r{bufs;length;[lh]=!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(Fs(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Fs(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=ch(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ch(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(Fs(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 Se(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Se(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 u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){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(!Fs(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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let h=u;h>=0;h--){let g=this.get(l+h);if(n[h]!==g){f=Math.max(1,h-a[g]);break}}if(f===0)return l}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=Le(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=_t(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=_t(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=_t(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=Le(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=_t(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=_t(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=_t(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=_t(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=_t(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var uh=async()=>{let r=await Zf("Ed25519"),e=await _0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function _0(r){return dn(Qf(r.public),Jf(r))}var fh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var so;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(so||(so={}));var mn=class r{static createFromProtobuf=async e=>{let t=so.decode(e),n=await dn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=hh(n,o,s),c=await(await no(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new y("envelope signature is not valid for the given domain",fh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=so.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ie(this.marshal(),e.marshal())}async validate(e){let t=hh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return ro(this.peerId.publicKey).verify(t.subarray(),this.signature)}},hh=(r,e,t)=>{let n=D(r),o=De(n.byteLength),s=De(e.length),i=De(t.length);return new be(o,n,s,e,i,t)};function dh(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 Vs=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",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(f===void 0)break;if(s*=e,s+=f,s>u||(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 ph=45,S0=15,gn=new Vs;function bc(r){if(!(r.length>S0))return gn.new(r).parseWith(()=>gn.readIPv4Addr())}function Ec(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ph))return gn.new(r).parseWith(()=>gn.readIPv6Addr())}function Ks(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ph))return gn.new(r).parseWith(()=>gn.readIPAddr())}var b1=parseInt("0xFFFF",16),E1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function yn(r){return!!bc(r)}function wn(r){return!!Ec(r)}function Hs(r){return!!Ks(r)}var yh=yn,N0=wn,xc=function(r){let e=0;if(r=r.toString().trim(),yh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(N0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=yh(t[n]),i;s&&(i=xc(t[n]),t[n]=K(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let 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++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},wh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var bn={},vc={},k0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];k0.forEach(r=>{let e=D0(...r);vc[e.code]=e,bn[e.name]=e});function D0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(vc[r]!=null)return vc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(bn[r]!=null)return bn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var nA=X("ip4"),oA=X("ip6"),sA=X("ipcidr");function Sc(r,e){switch(X(r).code){case 4:case 41:return O0(e);case 42:return _c(e);case 6:case 273:case 33:case 132:return xh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return _c(e);case 421:return V0(e);case 444:return Eh(e);case 445:return Eh(e);case 466:return F0(e);case 481:return globalThis.encodeURIComponent(_c(e));default:return K(e,"base16")}}function Ic(r,e){switch(X(r).code){case 4:return bh(e);case 41:return bh(e);case 42:return Rc(e);case 6:case 273:case 33:case 132:return Bc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Rc(e);case 421:return U0(e);case 444:return K0(e);case 445:return H0(e);case 466:return M0(e);case 481:return Rc(globalThis.decodeURIComponent(e));default:return D(e,"base16")}}var Ac=Object.values(Yt).map(r=>r.decoder),P0=function(){let r=Ac[0].or(Ac[1]);return Ac.slice(2).forEach(e=>r=r.or(e)),r}();function bh(r){if(!Hs(r))throw new Error("invalid ip address");return xc(r)}function O0(r){let e=wh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Hs(e))throw new Error("invalid ip address");return e}function Bc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function xh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Rc(r){let e=D(r),t=Uint8Array.from(De(e.length));return Se([t,e],t.length+e.length)}function _c(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return K(r)}function U0(r){let e;r[0]==="Q"||r[0]==="1"?e=gr(ne.decode(`z${r}`)).bytes:e=nt.parse(r).multihash.bytes;let t=Uint8Array.from(De(e.length));return Se([t,e],t.length+e.length)}function M0(r){let e=P0.decode(r),t=Uint8Array.from(De(e.length));return Se([t,e],t.length+e.length)}function F0(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+K(t,"base64url")}function V0(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return K(t,"base58btc")}function K0(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=Ge.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=Bc(n);return Se([t,o],t.length+o.length)}function H0(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=Ge.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=Bc(n);return Se([t,o],t.length+o.length)}function Eh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=K(e,"base32"),o=xh(t);return`${n}:${o}`}function vh(r){r=Tc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Rh("invalid address: "+r);if(a.path===!0){n=Tc(o.slice(s).join("/")),e.push([a.code,Ic(a.code,n)]),t.push([a.code,n]);break}let c=Ic(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Sc(a.code,c)])}return{string:Ah(t),bytes:Nc(e),tuples:e,stringTuples:t,path:n}}function Cc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=pe(s),a=X(s),c=$0(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Rh("Invalid address Uint8Array: "+K(r,"base16"));e.push([s,u]);let f=Sc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Ah(t),tuples:e,stringTuples:t,path:n}}function Ah(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Tc(e.join("/"))}function Nc(r){return Se(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(De(t.code));return e.length>1&&e[1]!=null&&(n=Se([n,e[1]])),n}))}function $0(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function Tc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Rh(r){return new Error("Error parsing address: "+r)}var q0=Symbol.for("nodejs.util.inspect.custom"),Lc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),G0=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],$s=class r{bytes;#e;#t;#s;#a;[Lc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Cc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=vh(e)}else if(cr(e))t=Cc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[g,d]of this.stringTuples())g===l.code&&(s=`%${d??""}`),G0.includes(g)&&(t=i.name,o=443,n=`${d??""}${s}`,e=g===f.code?6:4),(g===i.code||g===a.code)&&(t=X(g).name,o=parseInt(d??"")),(g===c.code||g===u.code)&&(t=X(g).name,n=`${d??""}${s}`,e=g===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Nc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===bn.p2p.code&&e.push([n,o]),n===bn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?K(ne.decode(`z${n}`),"base58btc"):K(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=En.get(t.name);if(n==null)throw new y(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>re(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[q0](){return`Multiaddr(${this.#e})`}};var En=new Map;function cr(r){return!!r?.[Lc]}function re(r){return new $s(r)}var _h="libp2p-peer-record",Sh=Uint8Array.from([3,1]);var io;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Ve(s,n.codec()),n.decode=s=>Fe(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Ve(n,r.codec()),r.decode=n=>Fe(n,r.codec())})(io||(io={}));var Nr=class r{static createFromProtobuf=e=>{let t=io.decode(e),n=hn(t.peerId),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=_h;static CODEC=Sh;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=io.encode({peerId:this.peerId.toBytes(),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||!dh(this.multiaddrs,e.multiaddrs))}};function z0(r){return r[Symbol.asyncIterator]!=null}function Y0(r){if(z0(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 ao=Y0;var Dc=Ht(Bh(),1);var lo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Pc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Th=r=>globalThis.DOMException===void 0?new Pc(r):new DOMException(r),Ch=r=>{let e=r.reason===void 0?Th("This operation was aborted."):r.reason;return e instanceof Error?e:Th(e)};function uo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(Ch(h)),h.addEventListener("abort",()=>{f(Ch(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new lo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Oc(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 fo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Oc(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var lr=class extends Dc.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:fo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#R(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=uo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof lo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var ur={},xn=r=>{r.addEventListener("message",e=>{xn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{xn.dispatchEvent("message",r,e)})};xn.addEventListener=(r,e)=>{ur[r]==null&&(ur[r]=[]),ur[r].push(e)};xn.removeEventListener=(r,e)=>{ur[r]!=null&&(ur[r]=ur[r].filter(t=>t===e))};xn.dispatchEvent=function(r,e,t){ur[r]!=null&&ur[r].forEach(n=>n(e,t))};var Uc=xn;var Mc="lock:worker:request-read",Fc="lock:worker:release-read",Vc="lock:master:grant-read",Kc="lock:worker:request-write",Hc="lock:worker:release-write",$c="lock:master:grant-write";var Nh=(r=21)=>Math.random().toString().substring(2);var Lh=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},kh=(r,e,t,n)=>async()=>{let o=Nh();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},X0={singleProcess:!1},Dh=r=>{if(r=Object.assign({},X0,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Uc.addEventListener("message",Lh(t,"requestReadLock",Mc,Fc,Vc)),Uc.addEventListener("message",Lh(t,"requestWriteLock",Kc,Hc,$c)),t}return{isWorker:!0,readLock:t=>kh(t,Mc,Vc,Fc),writeLock:t=>kh(t,Kc,$c,Hc)}};var Lr={},fr;async function qc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>uo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Z0=(r,e)=>{if(fr.isWorker===!0)return{readLock:fr.readLock(r,e),writeLock:fr.writeLock(r,e)};let t=new lr({concurrency:1}),n;return{async readLock(){if(n!=null)return qc(n,e);n=new lr({concurrency:e.concurrency,autoStart:!1});let o=n,s=qc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,qc(t,e)}}},Q0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Gc(r){let e=Object.assign({},Q0,r);return fr==null&&(fr=Dh(e),fr.isWorker!==!0&&(fr.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),fr.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=Z0(e.name,e)),Lr[e.name]}var Be={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var vn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ve(i,o.codec()),o.decode=i=>Fe(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),zs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=zs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ve(i,o.codec()),o.decode=i=>Fe(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Gs.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Gs.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Ve(o,r.codec()),r.decode=o=>Fe(o,r.codec())})(vn||(vn={}));var Gs;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(Gs||(Gs={}));var zs;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ve(t,r.codec()),r.decode=t=>Fe(t,r.codec())})(zs||(zs={}));function An(r,e){let t=vn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=ah({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",Ph=new TextEncoder().encode(Ft),Ys=Ph[0],kr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(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]!==Ys)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}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=Ph),this._buf[0]!==Ys){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ys,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ys;)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(Ft).slice(1)}type(){return J0(this.baseNamespace())}name(){return ey(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?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(),...ty(e.map(t=>t.namespaces()))])}};function J0(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function ey(r){let e=r.split(":");return e[e.length-1]}function ty(r){return[].concat(...r)}var zc="/peers/";function Rn(r){if(!Ro(r)||r.type==null)throw new y("Invalid PeerId",Be.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new kr(`${zc}${e}`)}async function Oh(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=re(o.multiaddr)),!cr(o.multiaddr))throw new y("Multiaddr was invalid",Be.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function js(r,e,t,n){if(e==null)throw new y("Invalid PeerData",Be.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!ie(e.publicKey,r.publicKey))throw new y("publicKey bytes do not match peer id publicKey bytes",Be.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new y("peer id did not match existing peer id",Be.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ws(l,{validate:Uh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ws(l,{validate:Mh,map:Fh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,g]of l)g==null?a.delete(h):a.set(h,g);a=Ws([...a.entries()],{validate:Uh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[g,d]of l)d==null?h.delete(g):h.set(g,d);c=Ws([...h.entries()],{validate:Mh,map:Fh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Oh(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,h)=>l.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function Ws(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 Uh(r,e){if(typeof r!="string")throw new y("Metadata key must be a string",Be.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new y("Metadata value must be a Uint8Array",Be.ERR_INVALID_PARAMETERS)}function Mh(r,e){if(typeof r!="string")throw new y("Tag name must be a string",Be.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new y("Tag value must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new y("Tag value must be between 0-100",Be.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new y("Tag ttl must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new y("Tag ttl must be between greater than 0",Be.ERR_INVALID_PARAMETERS)}}function Fh(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Xs(r,e,t){let n=r.toString().split("/")[2],o=Ge.decode(n),s=hn(o),i=t.get(s);if(i!=null)return i;let a=An(s,e);return t.set(s,a),a}function ry(r,e){return r==null?{}:{prefix:zc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Xs(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Xs(n.key,n.value,e),Xs(o.key,o.value,e)))}}var Zs=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Gc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Rn(e))}async delete(e){if(this.peerId.equals(e))throw new y("Cannot delete self peer",Be.ERR_INVALID_PARAMETERS);await this.datastore.delete(Rn(e))}async load(e){let t=await this.datastore.get(Rn(e));return An(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(ry(e??{},t))){let s=Xs(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Rn(e)),n=An(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=vn.encode(t);return n!=null&&ie(s,n)?{peer:An(e,s),previous:o,updated:!1}:(await this.datastore.put(Rn(e),s),{peer:An(e,s),previous:o,updated:!0})}};var Qs=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 Zs(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await ao(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mn.openAndCertify(e,Nr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Nr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mn.createFromProtobuf(s.peerRecordEnvelope),a=Nr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!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 ny(r){return r[Symbol.asyncIterator]!=null}function oy(r){if(ny(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yc=oy;function sy(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 Vh=sy;function iy(r){return r[Symbol.asyncIterator]!=null}function ay(r,e){let t=0;if(iy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Vh(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 await(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 Dr=ay;function cy(r){return r[Symbol.asyncIterator]!=null}function ly(r,e){return cy(r)?async function*(){yield*(await ao(r)).sort(e)}():function*(){yield*ao(r).sort(e)}()}var Wc=ly;function uy(r){return r[Symbol.asyncIterator]!=null}function fy(r,e){return uy(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 jc=fy;var Js=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 Yc(this.putMany(e,n)),e=[],await Yc(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=Dr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Dr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Wc(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Dr(n,()=>o++>=s)}return e.limit!=null&&(n=jc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Dr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Dr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Wc(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Dr(n,()=>s++>=o)}return e.limit!=null&&(n=jc(n,e.limit)),n}};var $h=Ht(Xc(),1);function qh(r){return r=r??new Error("Not Found"),(0,$h.default)(r,"ERR_NOT_FOUND")}var ei=class extends Js{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw qh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new kr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new kr(e)}};function Gh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var py=r=>r;function Zc(r,e){let t=r.getPeerId();return t!=null&&we(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var ti=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??py,this._updatePeerStoreAddresses=Gh(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>re(t))).map(t=>t.getPeerId()===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",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){e=Zc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Zc(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=Zc(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>re(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Qc=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=Ms())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>$l(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")}},my=["metrics","connectionProtector","dns"],gy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function zh(r={}){let e=new Qc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!gy.includes(o)){let i=e.components[o];if(i==null&&!my.includes(o))throw new y(`${o} not set`,"ERR_SERVICE_MISSING");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}})}var Wh=Ht(Yh(),1),yy=["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"],wy=yy.map(r=>new Wh.Netmask(r));function by(r){for(let e of wy)if(e.contains(r))return!0;return!1}function Ey(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function ri(r){return yn(r)?by(r):wn(r)?Ey(r):void 0}function jh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ri(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var xy=r=>r.toString().split("/").slice(1),po=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),W=r=>({match:e=>po(t=>t===r).match(e),pattern:r}),si=()=>({match:r=>po(e=>typeof e=="string").match(r),pattern:"{string}"}),ii=()=>({match:r=>po(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Te=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ne.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ni=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{da.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Ee=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),rt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=xy(o);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{matches:t,exactMatch:n}}var el=Q(W("dns4"),si()),tl=Q(W("dns6"),si()),rl=Q(W("dnsaddr"),si()),Xh=Q(W("dns"),si()),CR=fe(el),NR=fe(tl),LR=fe(rl),kR=fe(rt(Xh,rl,el,tl)),Zh=Q(W("ip4"),po(yn)),Qh=Q(W("ip6"),po(wn)),Jh=rt(Zh,Qh),xt=rt(Jh,Xh,el,tl,rl),DR=fe(xt),PR=fe(Zh),OR=fe(Qh),UR=fe(Jh),nl=Q(xt,W("tcp"),ii()),mo=Q(xt,W("udp"),ii()),MR=fe(nl),FR=fe(mo),ol=Q(mo,W("quic")),ai=Q(mo,W("quic-v1")),vy=rt(ol,ai),VR=fe(ol),KR=fe(ai),Jc=rt(xt,nl,mo,ol,ai),ed=rt(Q(Jc,W("ws"),Ee(Te()))),HR=fe(ed),td=rt(Q(Jc,W("wss"),Ee(Te())),Q(Jc,W("tls"),W("ws"),Ee(Te()))),$R=fe(td),rd=Q(mo,W("webrtc-direct"),Ee(ni()),Ee(ni()),Ee(Te())),qR=fe(rd),nd=Q(ai,W("webtransport"),Ee(ni()),Ee(ni()),Ee(Te())),GR=fe(nd),oi=rt(ed,td,Q(nl,Ee(Te())),Q(vy,Ee(Te())),Q(xt,Ee(Te())),rd,nd,Te()),zR=fe(oi),Ay=Q(oi,W("p2p-circuit"),Te()),go=fe(Ay),Ry=rt(Q(oi,W("p2p-circuit"),W("webrtc"),Ee(Te())),Q(oi,W("webrtc"),Ee(Te())),W("webrtc")),YR=fe(Ry),_y=rt(Q(xt,W("tcp"),ii(),W("http"),Ee(Te())),Q(xt,W("http"),Ee(Te()))),WR=fe(_y),Sy=rt(Q(xt,W("tcp"),rt(Q(W("443"),W("http")),Q(ii(),W("https"))),Ee(Te())),Q(xt,W("tls"),W("http"),Ee(Te())),Q(xt,W("https"),Ee(Te()))),jR=fe(Sy);function sl(r){try{let{address:e}=r.nodeAddress();return!!ri(e)}catch{return!0}}function Iy(r,e){let t=sl(r.multiaddr),n=sl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function By(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Ty(r,e){let t=go.exactMatch(r.multiaddr),n=go.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _n(r,e){let t=Iy(r,e);if(t!==0)return t;let n=Ty(r,e);return n!==0?n:By(r,e)}var hr=class extends Event{constructor(e,t){super(e),this.detail=t}};function ci(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var il=60;function li(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:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??il,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var Cy=4;function al(r,e={}){let t=new lr({concurrency:e.queryConcurrency??Cy});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ci(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new hr("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=li(await a.json());return o.onProgress?.(new hr("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function od(){return[al("https://cloudflare-dns.com/dns-query"),al("https://dns.google/resolve")]}var ad=Ht(id(),1);var cl=class{lru;constructor(e){this.lru=(0,ad.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 li({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:Ze[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??il)*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 cd(r){return new cl(r)}var Ny=1e3,ui=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=cd(e.cacheSize??Ny),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["."]=od())}async query(e,t={}){let n=ci(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new hr("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new hr("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function ld(r={}){return new ui(r)}var Ly=32,{code:ky}=X("dnsaddr"),Pr=async function(e,t={}){let n=t.maxRecursiveDepth??Ly;if(n===0)throw new y("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===ky)??[],i=await(t?.dns??ld()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=re(f);if(f.startsWith("/dnsaddr")){let h=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(g=>g.toString()))}else c.push(l.toString())}return c};var wd=Ht(yd(),1),di=wd.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var B;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(B||(B={}));var Fy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Pr},addressSorter:_n},transportManager:{faultTolerance:$t.FATAL_ALL}};async function bd(r){let e=di(Fy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new y(Vt.ERR_PROTECTOR_REQUIRED,B.ERR_PROTECTOR_REQUIRED);if(!(await dn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new y("Private key doesn't match peer id",B.ERR_INVALID_KEY);return e}var Ed=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Vy=new WeakMap;function Ky({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Ed());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Ed())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((h,g)=>{i=()=>{f(),h(n)},a=g,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Vy.set(l,()=>{c(s),s=null,i()}),l}}var Hy=Ky(),xd=Hy;var pi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new ul}async 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 y("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await xd(a)}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)}},ul=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 mi(r){if(Ro(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:we(t),r.forEach(n=>{if(!cr(n))throw new y("Invalid Multiaddr",B.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}else{let s=we(o);if(e==null||!e.equals(s))throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var gi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Bn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new gi(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 gi(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 fl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function yi(r={}){return $y(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 $y(r,e){e=e??{};let t=e.onEnd,n=new Bn,o,s,i,a=ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,w)=>{s=x=>{s=null,n.push(x);try{m(r(n))}catch(b){w(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ce()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Bn,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},h=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),g=()=>(n=new Bn,h(),{done:!0}),d=m=>(h(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:d,push:l,end:h,get readableLength(){return n.size},onEmpty:async m=>{let w=m?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,b;w!=null&&(x=new Promise((A,v)=>{b=()=>{v(new fl)},w.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&w!=null&&w?.removeEventListener("abort",b)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return p.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},o}var hl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Tn(r,e,t,n){let o=new hl(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(h){a(),i(h);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var wi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function dr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new wi(t?.errorMessage,t?.errorCode));let n,o=new wi(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var bi=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=ce(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new qt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function qy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ei=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=qy(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ue(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new qt),this.cleanup())}async join(e={}){let t=new bi(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dr(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)})}};var Cn=class extends At{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let 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){t?.signal?.throwIfAborted();let n=new Ei(e,t),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("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new qt)}),this.clear()}async onEmpty(e){this.size!==0&&await Tn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Tn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Tn(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=yi({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)},i=()=>{n()},a=()=>{n(new y("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var xi=class extends Cn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var vi="last-dial-failure";var Ai=5,Ri=100,_i=50,Si=1e3*60*7;var Or={minConnections:Ai,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Si,autoDialDiscoveredPeersDebounce:10},Ii=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Or.minConnections,this.autoDialPriority=t.autoDialPriority??Or.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Or.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Or.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Or.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Or.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new xi({concurrency:t.autoDialConcurrency??Or.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ft(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,h=i.get(f.id)??0;return l>h?-1:l<h?1:0}).filter(u=>{let f=u.metadata.get(vi);if(f==null)return!0;let l=parseInt(K(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var zy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function vd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??zy;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Ad={maxConnections:Ri,allow:[]},Bi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ad.maxConnections,this.allow=t.allow??Ad.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Xe;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await vd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}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 Ti=class extends Cn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function yo(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.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}async function Rd(r,e){let t=!1;for(let o of En.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var wo={addressSorter:_n,maxParallelDials:_i,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Pr}},Ci=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??wo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??wo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??wo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??wo.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ue(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))En.set(n,o);this.queue=new Ti({concurrency:t.maxParallelDials??wo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ue(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=mi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new y("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let h of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new y("Peer had more than maxPeerAddrsToDial",B.ERR_TOO_MANY_ADDRESSES);f++;try{let g=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),g}catch(g){if(this.log.error("dial failed to %a",h.multiaddr,g),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[vi]:D(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new y(g.message,So);l.push(g)}}throw l.length===1?l[0]:new _o(l,"All multiaddr dials failed",B.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??El,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=yo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ue(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:re(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new y("Tried to dial self",B.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new y("The dial request is blocked by gater.allowDialPeer",B.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(l){if(l.code!==B.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...l.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(l){l.code!==B.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let h=await Rd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(g=>({multiaddr:g,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let h=l.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let l of i){let h=l.multiaddr.toString(),g=a.get(h);if(g!=null){g.isCertified=g.isCertified||l.isCertified||!1;continue}a.set(h,l)}let c=[...a.values()];if(c.length===0)throw new y("The dial request has no valid addresses",B.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new y("The connection gater denied all addresses in the dial request",B.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}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.runOnTransientConnection===!1?n.find(o=>!go.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var El=50,Kt={minConnections:Ai,maxConnections:Ri,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Si,autoDialDiscoveredPeersDebounce:10},Ni=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kt.maxConnections;let n=t.minConnections??Kt.minConnections;if(this.maxConnections<n)throw new y("Connection Manager maxConnections must be greater than minConnections",B.ERR_INVALID_PARAMETERS);this.connections=new Xe,this.started=!1,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.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>re(o)),this.deny=(t.deny??[]).map(o=>re(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new pi({points:t.inboundConnectionThreshold??Kt.inboundConnectionThreshold,duration:1}),this.autoDial=new Ii({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Kt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Kt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Kt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Kt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??Kt.autoDialMaxQueueLength}),this.connectionPruner=new Bi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ci(e,{addressSorter:t.addressSorter??_n,maxParallelDials:t.maxParallelDials??_i,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Pr},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;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.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Hl)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}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.isStarted())throw new y("Not started",B.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=mi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??El}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};function jy(r){return r[Symbol.asyncIterator]!=null}function Xy(...r){let e=[];for(let t of r)jy(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=yi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var bo=Xy;var Li=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}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 y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of bo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new y(Vt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new y(Vt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var ki=globalThis.CustomEvent??Event;async function*xl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ce(),a=ce(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=ce(),await i.promise),f)break;let p={done:!1};s.push(p),d().then(m=>{p.done=!0,p.ok=!0,p.value=m,o.dispatchEvent(new ki("task-complete"))},m=>{p.done=!0,p.err=m,o.dispatchEvent(new ki("task-complete"))})}c=!0,o.dispatchEvent(new ki("task-complete"))}catch(d){u=d,o.dispatchEvent(new ki("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*h(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*g(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let p=s[d];if(s.splice(d,1),d--,p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}for(;;){if(l()||(a=ce(),await a.promise),u!=null)throw u;if(n?yield*h():yield*g(),c&&s.length===0)break}}var Di=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??[]}async findPeer(e,t){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new y("Should not try to find self",B.ERR_FIND_SELF);let n=this,o=bo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new y(Vt.NOT_FOUND,B.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of xl(async function*(){let i=bo(...n.routers.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",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Pi=class extends At{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,ue(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,ue(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=yo([this.shutdownController.signal,e?.signal]);ue(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ce(),yield(await Tn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ue(1/0,this.walkController.signal);let e=yo([this.walkController.signal,this.shutdownController.signal]);ue(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(yt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await dr(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var vl=32,Al=64,Oi=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,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)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new y(`No handler registered for protocol ${e}`,B.ERR_NO_HANDLER_FOR_PROTOCOL);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))throw new y(`Handler already registered for protocol ${e}`,B.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=di.bind({ignoreUndefined:!0})({maxInboundStreams:vl,maxOutboundStreams:Al},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new y("invalid topology",B.ERR_INVALID_PARAMETERS);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))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==B.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Rl=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 _d(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Rl({name:e,metrics:t}):n=new Map,n}var Ui=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=new Map,this.listeners=_d({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??$t.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new y("Transport must have a valid tag",B.ERR_INVALID_KEY);if(this.transports.has(t))throw new y(`There is already a transport with the tag ${t}`,B.ERR_DUPLICATE_TRANSPORT);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 y(`No transport available for address ${String(e)}`,B.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=B.ERR_TRANSPORT_DIAL_FAILED),o}}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 y("Not started",B.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let h=l.findIndex(g=>g===f);l.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==$t.NO_FATAL)throw new y(`Transport (${n}) could not listen on any available address`,B.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===$t.FATAL_ALL)throw new y(n,B.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Ce="/multistream/1.0.0";var _l=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ce(),this.haveNext=ce()}[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=ce(),e}async throw(e){return this.ended=!0,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 await this._push(void 0),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 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=ce(),await dr(this.readNext.promise,t?.signal,t)}};function Sd(){return new _l}var Mi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Sl=class extends Mi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Id(r,e){let t=Sd();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new be;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Sl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:h}=await Promise.race([n.next(),u]);return l===!0?new be:h}for(;o.byteLength<i;){let{value:l,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new Mi("unexpected end of input","ERR_UNEXPECTED_EOF");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Fi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function Eo(r,e={}){let t=Id(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??De;return{read:async i=>{let a=-1,c=new be;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Fi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Fi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new be(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new be(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Zy=D(`
8
+ `);async function Ur(r,e,t){await r.write(e,t)}async function Bd(r,e,t){await r.writeV(e,t)}async function Qy(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Zy[0])throw e.log.error("Invalid mss message - missing newline",t),new y("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function pr(r,e){let t=await Qy(r,e);return K(t.subarray())}async function xo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Jy(r,e[0],t);let n=Eo(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Ce,o);let s=D(`${Ce}
9
9
  `),i=D(`${o}
10
10
  `);await Bd(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await pr(n,t);if(t.log.trace('select: read "%s"',a),a===Ce&&(t.log.trace("select: reading protocol response"),a=await pr(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Ur(n,D(`${c}
11
- `),t),t.log.trace("select: reading protocol response");let u=await pr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new y("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function ew(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ce(),c=!1,u=!1,f=ce(),l=!1,h=!1,g=ce(),d=Eo({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async x=>{let{sink:b}=d.unwrap();await b(async function*(){let A=!1;for await(let v of x){if(u&&await f.promise,c)yield v;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Ce,e,v.byteLength);let S=`${e}
11
+ `),t),t.log.trace("select: reading protocol response");let u=await pr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new y("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Jy(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ce(),c=!1,u=!1,f=ce(),l=!1,h=!1,g=ce(),d=Eo({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async x=>{let{sink:b}=d.unwrap();await b(async function*(){let A=!1;for await(let v of x){if(u&&await f.promise,c)yield v;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Ce,e,v.byteLength);let S=`${e}
12
12
  `;yield new be(Uint8Array.from([19]),D(`${Ce}
13
13
  `),De(S.length),D(S),v).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Ce,e,v.byteLength),c=!0,u=!1,f.resolve(),p().catch(C=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,C)})}A=!0}A||await p()}())};async function p(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await m()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await w())}finally{i=!1,s=!0,a.resolve()}}async function m(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Ce,e),await d.writeV([D(`${Ce}
14
14
  `),D(`${e}
15
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Ce,e)}finally{c=!0,u=!1,f.resolve()}}async function w(){if(h){await g.promise;return}h=!0;try{t.log.trace("optimistic: reading multistream select header");let x=await pr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',x),x===Ce&&(x=await pr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',x,e),x!==e)throw new y("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{l=!0,h=!1,g.resolve()}}if(r.source=async function*(){await p(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*d.unwrap().source}(),r.closeRead!=null){let x=r.closeRead.bind(r);r.closeRead=async b=>{s||await p().catch(A=>{t.log.error("could not negotiate protocol before close read",A)}),await x(b)}}if(r.closeWrite!=null){let x=r.closeWrite.bind(r);r.closeWrite=async b=>{s||await p().catch(A=>{t.log.error("could not negotiate protocol before close write",A)}),await x(b)}}if(r.close!=null){let x=r.close.bind(r);r.close=async b=>{let A=[];u&&A.push(f.promise),h&&A.push(g.promise),A.length>0?await dr(Promise.all(A),b?.signal):(s=!0,i=!1,a.resolve()),await x(b)}}return{stream:r,protocol:e}}function Ki(r){return r[Symbol.asyncIterator]!=null}var Hi=r=>{let e=pe(r),t=Le(e);return De(r,t),Hi.bytes=e,t};Hi.bytes=0;function $i(r,e){e=e??{};let t=e.lengthEncoder??Hi;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Ki(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}$i.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Hi;return new be(t(r.byteLength),r)};var Nn=Ht(jc(),1);var tw=8,rw=1024*1024*4,Mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Mr||(Mr={}));var Il=r=>{let e=it(r);return Il.bytes=pe(e),e};Il.bytes=0;function Sl(r,e){let t=new be,n=Mr.LENGTH,o=-1,s=e?.lengthDecoder??Il,i=e?.maxLengthLength??tw,a=e?.maxDataLength??rw;function*c(){for(;t.byteLength>0;){if(n===Mr.LENGTH)try{if(o=s(t),o<0)throw(0,Nn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Nn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Mr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,Nn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Mr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Mr.LENGTH}}}return Ki(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Nn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Nn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Sl.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 Sl(n,{...e??{},onLength:s=>{t=s}})};async function vo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Eo(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await pr(n,t);if(t.log.trace('handle: read "%s"',o),o===Ce){t.log.trace('handle: respond with "%s" for "%s"',Ce,o),await Ur(n,D(`${Ce}
15
+ `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Ce,e)}finally{c=!0,u=!1,f.resolve()}}async function w(){if(h){await g.promise;return}h=!0;try{t.log.trace("optimistic: reading multistream select header");let x=await pr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',x),x===Ce&&(x=await pr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',x,e),x!==e)throw new y("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{l=!0,h=!1,g.resolve()}}if(r.source=async function*(){await p(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*d.unwrap().source}(),r.closeRead!=null){let x=r.closeRead.bind(r);r.closeRead=async b=>{s||await p().catch(A=>{t.log.error("could not negotiate protocol before close read",A)}),await x(b)}}if(r.closeWrite!=null){let x=r.closeWrite.bind(r);r.closeWrite=async b=>{s||await p().catch(A=>{t.log.error("could not negotiate protocol before close write",A)}),await x(b)}}if(r.close!=null){let x=r.close.bind(r);r.close=async b=>{let A=[];u&&A.push(f.promise),h&&A.push(g.promise),A.length>0?await dr(Promise.all(A),b?.signal):(s=!0,i=!1,a.resolve()),await x(b)}}return{stream:r,protocol:e}}function Vi(r){return r[Symbol.asyncIterator]!=null}var Ki=r=>{let e=pe(r),t=Le(e);return De(r,t),Ki.bytes=e,t};Ki.bytes=0;function Hi(r,e){e=e??{};let t=e.lengthEncoder??Ki;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Vi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Hi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ki;return new be(t(r.byteLength),r)};var Nn=Ht(Xc(),1);var ew=8,tw=1024*1024*4,Mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Mr||(Mr={}));var Tl=r=>{let e=it(r);return Tl.bytes=pe(e),e};Tl.bytes=0;function Bl(r,e){let t=new be,n=Mr.LENGTH,o=-1,s=e?.lengthDecoder??Tl,i=e?.maxLengthLength??ew,a=e?.maxDataLength??tw;function*c(){for(;t.byteLength>0;){if(n===Mr.LENGTH)try{if(o=s(t),o<0)throw(0,Nn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Nn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Mr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,Nn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Mr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Mr.LENGTH}}}return Vi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Nn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Nn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Bl.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 Bl(n,{...e??{},onLength:s=>{t=s}})};async function vo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Eo(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await pr(n,t);if(t.log.trace('handle: read "%s"',o),o===Ce){t.log.trace('handle: respond with "%s" for "%s"',Ce,o),await Ur(n,D(`${Ce}
16
16
  `),t),t.log.trace('handle: responded with "%s" for "%s"',Ce,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Ur(n,D(`${o}
17
- `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new be(...e.map(i=>$i.single(D(`${i}
17
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new be(...e.map(i=>Hi.single(D(`${i}
18
18
  `))),D(`
19
19
  `));t.log.trace('handle: respond with "%s" for %s',e,o),await Ur(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Ur(n,D(`na
20
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var ow=500,Bl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Fl]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new y("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new y("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(ow);ue(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Cd(r){return new Bl(r)}var sw=3e4;function iw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return El}function aw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??xl}function Nd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var qi=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new y(`The multiaddr connection is blocked by gater.${n}`,B.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new y("connection denied",B.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new y("inbound upgrade timeout",So))};u.addEventListener("abort",f,{once:!0}),ue(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new y("The multiaddr connection is blocked by gater.acceptConnection",B.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),l=await h.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let h={...l,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new y("inbound connection that skipped encryption must have a peer id",B.ERR_INVALID_MULTIADDR);let g=we(h);c="native",s=g}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...l,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=we(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new y("Encryption was skipped but no peer id was passed",B.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:w}=await vo(d,p,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",w);let x=iw(w,this.components.registrar);if(Nd(w,"inbound",l)===x){let A=new y(`Too many inbound protocol streams for protocol "${w}" - limit ${x}`,B.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=w,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[w]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:w})}).catch(async p=>{l.log.error("error handling incoming stream id %s",d.id,p.message,p.code,p.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,p={})=>{if(u==null)throw new y("Stream is not multiplexed",B.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(p.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(sw);ue(1/0,v),p={...p,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:w,protocol:x}=await xo(m,d,{...p,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=aw(x,this.components.registrar,p),A=Nd(x,"outbound",l);if(A>=b){let v=new y(`Too many outbound protocol streams for protocol "${x}" - ${A}/${b}`,B.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[x]}),m.source=w.source,m.sink=w.sink,m.protocol=x,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(w){throw l.log.error("could not create new stream for protocols %s",d,w),m.timeline.close==null&&m.abort(w),w.code!=null?w:new y(String(w),B.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(p){l.log.error("error closing connection after timeline close",p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{l.log.error("error thrown while dispatching connection:close event",p)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let g=()=>{throw new y("connection is not multiplexed",B.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Cd({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??g,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await vo(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new y(n.message,B.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await xo(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new y(o.message,B.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await xo(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await vo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}};var Ld="1.5.2-a3e8beabd",kd="libp2p";var Tl=class extends At{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new At,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Zi(a.type,{detail:a.detail}));return c||u},ue(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ms(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=zh({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:kd,version:Ld},logger:this.logger,events:t,datastore:e.datastore??new ei,connectionGater:jh(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Qs(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new qi(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Mi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Li(this.components,e.connectionManager)),this.configureComponent("registrar",new Ui(this.components)),this.configureComponent("addressManager",new ti(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Pi(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ki(this.components,{routers:i})),this.configureComponent("randomWalk",new Oi(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[zi]!=null&&(this.log("registering service %s for content routing",a),i.push(u[zi])),u[ji]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ji])),u[Yi]!=null&&(this.log("registering service %s for peer discovery",a),u[Yi].addEventListener?.("peer",f=>{this.#e(f)}))}}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")}catch(e){throw this.log.error("An error occurred starting libp2p",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 ft;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 y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){cr(e)&&(e=we(e.getPeerId()??"")),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 s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==B.ERR_NOT_FOUND)throw s}let n=_e([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return ro(o),await this.peerStore.patch(e,{publicKey:o}),o}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){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(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(new Error(B.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Dd(r={}){let e=r.peerId??=await ch();if(e.privateKey==null)throw new y("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await no(e.privateKey),new Tl(await bd(r))}async function lw(r={}){let e=await Dd(r);return r.start!==!1&&await e.start(),e}return Wd(uw);})();
20
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var nw=500,Cl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Kl]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new y("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new y("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(nw);ue(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Cd(r){return new Cl(r)}var ow=3e4;function sw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return vl}function iw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Al}function Nd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var $i=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new y(`The multiaddr connection is blocked by gater.${n}`,B.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new y("connection denied",B.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new y("inbound upgrade timeout",So))};u.addEventListener("abort",f,{once:!0}),ue(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new y("The multiaddr connection is blocked by gater.acceptConnection",B.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),l=await h.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let h={...l,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new y("inbound connection that skipped encryption must have a peer id",B.ERR_INVALID_MULTIADDR);let g=we(h);c="native",s=g}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...l,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=we(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new y("Encryption was skipped but no peer id was passed",B.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:w}=await vo(d,p,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",w);let x=sw(w,this.components.registrar);if(Nd(w,"inbound",l)===x){let A=new y(`Too many inbound protocol streams for protocol "${w}" - limit ${x}`,B.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=w,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[w]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:w})}).catch(async p=>{l.log.error("error handling incoming stream id %s",d.id,p.message,p.code,p.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,p={})=>{if(u==null)throw new y("Stream is not multiplexed",B.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(p.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(ow);ue(1/0,v),p={...p,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:w,protocol:x}=await xo(m,d,{...p,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=iw(x,this.components.registrar,p),A=Nd(x,"outbound",l);if(A>=b){let v=new y(`Too many outbound protocol streams for protocol "${x}" - ${A}/${b}`,B.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[x]}),m.source=w.source,m.sink=w.sink,m.protocol=x,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(w){throw l.log.error("could not create new stream for protocols %s",d,w),m.timeline.close==null&&m.abort(w),w.code!=null?w:new y(String(w),B.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(p){l.log.error("error closing connection after timeline close",p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{l.log.error("error thrown while dispatching connection:close event",p)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let g=()=>{throw new y("connection is not multiplexed",B.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Cd({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??g,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await vo(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new y(n.message,B.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await xo(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new y(o.message,B.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await xo(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await vo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}};var Ld="1.6.0-12106b5b0",kd="libp2p";var Nl=class extends At{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new At,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Xi(a.type,{detail:a.detail}));return c||u},ue(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ms(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=zh({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:kd,version:Ld},logger:this.logger,events:t,datastore:e.datastore??new ei,connectionGater:jh(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Qs(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new $i(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Ui(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ni(this.components,e.connectionManager)),this.configureComponent("registrar",new Oi(this.components)),this.configureComponent("addressManager",new ti(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Di(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Li(this.components,{routers:i})),this.configureComponent("randomWalk",new Pi(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Gi]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Gi])),u[Wi]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Wi])),u[zi]!=null&&(this.log("registering service %s for peer discovery",a),u[zi].addEventListener?.("peer",f=>{this.#e(f)}))}}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")}catch(e){throw this.log.error("An error occurred starting libp2p",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 ft;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 y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){cr(e)&&(e=we(e.getPeerId()??"")),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 s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==B.ERR_NOT_FOUND)throw s}let n=Se([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return ro(o),await this.peerStore.patch(e,{publicKey:o}),o}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){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(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(new Error(B.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Dd(r={}){let e=r.peerId??=await uh();if(e.privateKey==null)throw new y("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await no(e.privateKey),new Nl(await bd(r))}async function cw(r={}){let e=await Dd(r);return r.start!==!1&&await e.start(),e}return Wd(lw);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  pvtsutils/build/index.js: