diff --git "a/_next/static/chunks/659-cbbb4b3dad45579b.js" "b/_next/static/chunks/659-cbbb4b3dad45579b.js" new file mode 100644--- /dev/null +++ "b/_next/static/chunks/659-cbbb4b3dad45579b.js" @@ -0,0 +1,47 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[659],{55022:function(e,t,r){let n;var i=r(25566);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&void 0!==i&&"env"in i&&(e=i.env.DEBUG),e},t.useColors=function(){return"undefined"!=typeof window&&!!window.process&&("renderer"===window.process.type||!!window.process.__nwjs)||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(n=!1,()=>{n||(n=!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`."))}),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=r(11810)(t);let{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},11810:function(e,t,r){e.exports=function(e){function t(e){let r,i,s;let o=null;function a(...e){if(!a.enabled)return;let n=Number(new Date),i=n-(r||n);a.diff=i,a.prev=r,a.curr=n,r=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,n)=>{if("%%"===r)return"%";s++;let i=t.formatters[n];if("function"==typeof i){let t=e[s];r=i.call(a,t),e.splice(s,1),s--}return r}),t.formatArgs.call(a,e),(a.log||t.log).apply(a,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){let n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){let e=[...t.names.map(i),...t.skips.map(i).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];let n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t=r)&&!(t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(0==arguments.length)return this.size();var t=this._tail;return(this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t,r=e;if(r===(0|r)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(r>=n)&&!(r<-n)){r<0&&(r+=n),r=this._head+r&this._capacityMask;var s=this._list[r];if(e0;t--)this._list[r]=this._list[r=r-1+i&this._capacityMask];this._list[r]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(t=n-1-e;t>0;t--)this._list[r]=this._list[r=r+1+i&this._capacityMask];this._list[r]=void 0,this._tail=this._tail-1+i&this._capacityMask}return s}}},t.prototype.remove=function(e,t){var r,n,i=e,s=t;if(i===(0|i)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(i>=o)&&!(i<-o)&&!(t<1)){if(i<0&&(i+=o),1===t||!t)return(r=[,])[0]=this.removeOne(i),r;if(0===i&&i+t>=o)return r=this.toArray(),this.clear(),r;for(i+t>o&&(t=o-i),r=Array(t),n=0;n0;n--)this._list[i=i+1+a&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+a&this._capacityMask,n=t-1;n>0;n--)this._list[i=i+1+a&this._capacityMask]=void 0;return r}if(i0;n--)this.unshift(this._list[i=i-1+a&this._capacityMask]);for(i=this._head-1+a&this._capacityMask;s>0;)this._list[i=i-1+a&this._capacityMask]=void 0,s--;e<0&&(this._tail=i)}else{for(this._tail=i,i=i+t+a&this._capacityMask,n=o-(t+e);n>0;n--)this.push(this._list[i++]);for(i=this._tail;s>0;)this._list[i=i+1+a&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(!(arguments.length>2))return this.remove(r,t);var i,s,o,a=arguments.length,l=this._list.length,c=2;if(!n||r0&&(this._head=this._head+r+l&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+l&this._capacityMask);a>c;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(s[i-1])}else{var u=(s=Array(n-(r+t))).length;for(i=0;ithis._tail){for(r=this._head;r>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){return Math.max(1<=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){for(let e of(this.isStopped=!0,this.remove(),this.pullQueue))e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped){if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.pullQueue.push({resolve:e,reject:t})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},50762:function(e){e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,s){r[i]=s,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},37017:function(e,t,r){var n,i,s,o,a,l,c,u,h,d,p,f,g,m,y,b=r(25566);!(n="object"==typeof window?window:{}).HI_BASE32_NO_NODE_JS&&"object"==typeof b&&b.versions&&b.versions.node&&(n=r.g),i=!n.HI_BASE32_NO_COMMON_JS&&e.exports,s=r.amdO,o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},l=[0,0,0,0,0,0,0,0],c=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},u=function(e){for(var t,r,n="",i=e.length,s=0,o=0;s191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):c(s,n);for(var a=0;a191)&&c(s,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&c(s,n),r>1114111&&c(s,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode((r>>10)+55296)+String.fromCharCode((1023&r)+56320))}return n},h=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");e=e.replace(/=/g,"");for(var t,r,n,i,s,o,l,c,u=[],h=0,d=e.length,p=0,f=d>>3<<3;p>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255,u[h++]=(i<<4|s>>>1)&255,u[h++]=(s<<7|o<<2|l>>>3)&255,u[h++]=(l<<5|c)&255;var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255,u[h++]=(i<<4|s>>>1)&255):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],l=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255,u[h++]=(i<<4|s>>>1)&255,u[h++]=(s<<7|o<<2|l>>>3)&255),u},d=function(e){for(var t,r,n,i,s,a="",l=e.length,c=0,u=5*parseInt(l/5);c>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[(i<<3|s>>>5)&31]+o[31&s];var h=l-u;return 1===h?a+=o[(t=e.charCodeAt(c))>>>3]+o[t<<2&31]+"======":2===h?(t=e.charCodeAt(c++),r=e.charCodeAt(c),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(c++),r=e.charCodeAt(c++),n=e.charCodeAt(c),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(c++),r=e.charCodeAt(c++),n=e.charCodeAt(c++),i=e.charCodeAt(c),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[i<<3&31]+"="),a},p=function(e){var t,r,n,i,s,a,c,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(l[0]=l[5],l[1]=l[6],l[2]=l[7],c=p;d>6:(a<55296||a>=57344?l[c++]=224|a>>12:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),l[c++]=240|a>>18,l[c++]=128|a>>12&63),l[c++]=128|a>>6&63),l[c++]=128|63&a);p=c-5,d===f&&++d,d>f&&c<6&&(u=!0),t=l[0],c>4?(r=l[1],n=l[2],i=l[3],s=l[4],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[(i<<3|s>>>5)&31]+o[31&s]):1===c?h+=o[t>>>3]+o[t<<2&31]+"======":2===c?(r=l[1],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[r<<4&31]+"===="):3===c?(r=l[1],n=l[2],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[n<<1&31]+"==="):(r=l[1],n=l[2],i=l[3],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[i<<3&31]+"=")}while(!u);return h},f=function(e){for(var t,r,n,i,s,a="",l=e.length,c=0,u=5*parseInt(l/5);c>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[(i<<3|s>>>5)&31]+o[31&s];var h=l-u;return 1===h?a+=o[(t=e[c])>>>3]+o[t<<2&31]+"======":2===h?(t=e[c++],r=e[c],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[c++],r=e[c++],n=e[c],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[n<<1&31]+"==="):4===h&&(t=e[c++],r=e[c++],n=e[c++],i=e[c],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[i<<3&31]+"="),a},m={encode:function(e,t){var r="string"!=typeof e;return(r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r)?f(e):t?d(e):p(e)},decode:g=function(e,t){if(!t)return u(h(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,i,s,o,l,c,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)+String.fromCharCode((s<<4|o>>>1)&255)+String.fromCharCode((o<<7|l<<2|c>>>3)&255)+String.fromCharCode((c<<5|d)&255);var y=f-m;return 2===y?p+=String.fromCharCode(((r=a[e.charAt(g++)])<<3|(n=a[e.charAt(g++)])>>>2)&255):4===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)):5===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)+String.fromCharCode((s<<4|o>>>1)&255)):7===y&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],l=a[e.charAt(g++)],c=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)+String.fromCharCode((s<<4|o>>>1)&255)+String.fromCharCode((o<<7|l<<2|c>>>3)&255)),p}},g.asBytes=h,i?e.exports=m:(n.base32=m,s&&void 0!==(y=(function(){return m}).call(m,r,m,e))&&(e.exports=y))},12471:function(e,t,r){var n=r(25566);e.exports=function(){return!!("undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||void 0!==n&&"object"==typeof n.versions&&n.versions.electron||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},83524:function(e,t,r){var n,i=r(25566);!function(){"use strict";var s="input is invalid type",o="object"==typeof window,a=o?window:{};a.JS_SHA3_NO_WINDOW&&(o=!1);var l=!o&&"object"==typeof self;!a.JS_SHA3_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node?a=r.g:l&&(a=self);for(var c=!a.JS_SHA3_NO_COMMON_JS&&e.exports,u=r.amdO,h=!a.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),p=[4,1024,262144,67108864],f=[0,8,16,24],g=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],m=[224,256,384,512],y=[128,256],b=["hex","buffer","arrayBuffer","array","digest"],v={128:168,256:136},w=a.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,E=h&&(a.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)?function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer}:ArrayBuffer.isView,S=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw Error(s);if(h&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!E(e))throw Error(s);return[e,!1]},A=function(e){return 0===S(e)[0].length},I=function(e){for(var t=[],r=0;r>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function V(e,t,r){K.call(this,e,t,r)}K.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=S(e);e=t[0];for(var r,n,i=t[1],s=this.blocks,o=this.byteCount,a=e.length,l=this.blockCount,c=0,u=this.s;c>2]|=n<>2]|=(192|n>>6)<=57344?s[r>>2]|=(224|n>>12)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[c]<=o){for(this.start=r-o,this.block=s[l],r=0;r>=8,r=255&e;r>0;)i.unshift(r),e>>=8,r=255&e,++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},K.prototype.encodeString=function(e){var t=S(e);e=t[0];var r=t[1],n=0,i=e.length;if(r)for(var s=0;s=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++s)),n+=4)}else n=i;return n+=this.encode(8*n),this.update(e),n},K.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(t=1,e[0]=e[r];t>4&15]+d[15&e]+d[e>>12&15]+d[e>>8&15]+d[e>>20&15]+d[e>>16&15]+d[e>>28&15]+d[e>>24&15];o%t==0&&(H(r=I(r)),s=0)}return i&&(a+=d[(e=r[s])>>4&15]+d[15&e],i>1&&(a+=d[e>>12&15]+d[e>>8&15]),i>2&&(a+=d[e>>20&15]+d[e>>16&15])),a},K.prototype.arrayBuffer=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3,l=new Uint32Array(e=new ArrayBuffer(i?n+1<<2:a));o>8&255,l[e+2]=t>>16&255,l[e+3]=t>>24&255;a%r==0&&H(n=I(n))}return s&&(e=a<<2,t=n[o],l[e]=255&t,s>1&&(l[e+1]=t>>8&255),s>2&&(l[e+2]=t>>16&255)),l},V.prototype=new K,V.prototype.finalize=function(){return this.encode(this.outputBits,!0),K.prototype.finalize.call(this)};var H=function(e){var t,r,n,i,s,o,a,l,c,u,h,d,p,f,m,y,b,v,w,E,S,A,I,_,T,C,R,k,P,D,B,N,L,x,O,M,U,F,K,V,H,$,q,z,j,G,W,Y,Q,J,X,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],l=e[4]^e[14]^e[24]^e[34]^e[44],c=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],d=e[8]^e[18]^e[28]^e[38]^e[48],p=e[9]^e[19]^e[29]^e[39]^e[49],t=d^(o<<1|a>>>31),r=p^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(l<<1|c>>>31),r=s^(c<<1|l>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=l^(d<<1|p>>>31),r=c^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,f=e[0],m=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,k=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ea=e[31]<<9|e[30]>>>23,el=e[30]<<9|e[31]>>>23,$=e[40]<<18|e[41]>>>14,q=e[41]<<18|e[40]>>>14,x=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,Q=e[23]<<10|e[22]>>>22,D=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ec=e[42]<<2|e[43]>>>30,eu=e[43]<<2|e[42]>>>30,et=e[5]<<30|e[4]>>>2,er=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,v=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,X=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,L=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,T=e[7]<<28|e[6]>>>4,en=e[17]<<23|e[16]>>>9,ei=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,K=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,z=e[8]<<27|e[9]>>>5,j=e[9]<<27|e[8]>>>5,C=e[18]<<20|e[19]>>>12,R=e[19]<<20|e[18]>>>12,es=e[29]<<7|e[28]>>>25,eo=e[28]<<7|e[29]>>>25,V=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=f^~y&v,e[1]=m^~b&w,e[10]=_^~C&k,e[11]=T^~R&P,e[20]=x^~M&F,e[21]=O^~U&K,e[30]=z^~G&Y,e[31]=j^~W&Q,e[40]=et^~en&es,e[41]=er^~ei&eo,e[2]=y^~v&E,e[3]=b^~w&S,e[12]=C^~k&D,e[13]=R^~P&B,e[22]=M^~F&V,e[23]=U^~K&H,e[32]=G^~Y&J,e[33]=W^~Q&X,e[42]=en^~es&ea,e[43]=ei^~eo&el,e[4]=v^~E&A,e[5]=w^~S&I,e[14]=k^~D&N,e[15]=P^~B&L,e[24]=F^~V&$,e[25]=K^~H&q,e[34]=Y^~J&Z,e[35]=Q^~X&ee,e[44]=es^~ea&ec,e[45]=eo^~el&eu,e[6]=E^~A&f,e[7]=S^~I&m,e[16]=D^~N&_,e[17]=B^~L&T,e[26]=V^~$&x,e[27]=H^~q&O,e[36]=J^~Z&z,e[37]=X^~ee&j,e[46]=ea^~ec&et,e[47]=el^~eu&er,e[8]=A^~f&y,e[9]=I^~m&b,e[18]=N^~_&C,e[19]=L^~T&R,e[28]=$^~x&M,e[29]=q^~O&U,e[38]=Z^~z&G,e[39]=ee^~j&W,e[48]=ec^~et&en,e[49]=eu^~er&ei,e[0]^=g[n],e[1]^=g[n+1]};if(c)e.exports=B;else{for(L=0;LObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,l={concatArrays:!1,ignoreUndefined:!1},c=e=>{let t=[];for(let r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols)for(let r of Object.getOwnPropertySymbols(e))s.call(e,r)&&t.push(r);return t};function u(e){return Array.isArray(e)?function(e){let t=e.slice(0,0);return c(e).forEach(r=>{o(t,r,u(e[r]))}),t}(e):n(e)?function(e){let t=null===Object.getPrototypeOf(e)?Object.create(null):{};return c(e).forEach(r=>{o(t,r,u(e[r]))}),t}(e):e}let h=(e,t,r,n)=>(r.forEach(r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?o(e,r,p(e[r],t[r],n)):o(e,r,u(t[r])))}),e),d=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach(t=>{let a=[];for(let r=0;r!a.includes(e)),r)}),n};function p(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?d(e,t,r):n(t)&&n(e)?h(e,t,c(t),r):u(t)}e.exports=function(...e){let t=p(u(l),this!==a&&this||{},l),r={_:{}};for(let i of e)if(void 0!==i){if(!n(i))throw TypeError("`"+i+"` is not an Option Object");r=p(r,{_:i},t)}return r._}},33388:function(e){"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},44378:function(e){function t(e,t,r,n){return Math.round(e/r)+" "+n+(t>=1.5*r?"s":"")}e.exports=function(e,r){r=r||{};var n,i,s=typeof e;if("string"===s&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return 864e5*r;case"hours":case"hour":case"hrs":case"hr":case"h":return 36e5*r;case"minutes":case"minute":case"mins":case"min":case"m":return 6e4*r;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}(e);if("number"===s&&isFinite(e))return r.long?(n=Math.abs(e))>=864e5?t(e,n,864e5,"day"):n>=36e5?t(e,n,36e5,"hour"):n>=6e4?t(e,n,6e4,"minute"):n>=1e3?t(e,n,1e3,"second"):e+" ms":(i=Math.abs(e))>=864e5?Math.round(e/864e5)+"d":i>=36e5?Math.round(e/36e5)+"h":i>=6e4?Math.round(e/6e4)+"m":i>=1e3?Math.round(e/1e3)+"s":e+"ms";throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},37491:function(e,t){(function(){var e,r,n,i,s,o,a,l;l=function(e){return[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,s,o,a;for(t=[],i=s=0;s<=3&&0!==e.length;i=++s){if(i>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),s=n("A"),r=function(e){var t,r,a,l,c;for(l=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),c=a;a>>0;else if(16===t){if("a"<=e[a]&&e[a]<="f")l=l*t+(10+n(e[a])-o)>>>0;else if("A"<=e[a]&&e[a]<="F")l=l*t+(10+n(e[a])-s)>>>0;else break}else break;if(l>4294967295)throw Error("too large");a++}if(a===c)throw Error("empty octet");return[l,a]},e=function(){function e(e,t){var r,n,i;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(e=(i=e.split("/",2))[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else if(t||0===t)this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw Error("Invalid mask: empty");try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=l(this.netLong),this.mask=l(this.maskLong),this.hostmask=l(~this.maskLong),this.first=this.bitmask<=30?l(this.netLong+1):this.base,this.last=this.bitmask<=30?l(this.netLong+this.size-2):l(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?l(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return("string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e)?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(l(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(l(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=l,t.Netmask=e}).call(this)},66648:function(e,t,r){"use strict";r.d(t,{default:function(){return i.a}});var n=r(61669),i=r.n(n)},38173:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return v}});let n=r(99920),i=r(41452),s=r(57437),o=i._(r(2265)),a=n._(r(54887)),l=n._(r(28321)),c=r(80497),u=r(7103),h=r(93938);r(72301);let d=r(60291),p=n._(r(21241)),f={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function g(e,t,r,n,i,s,o){let a=null==e?void 0:e.src;e&&e["data-loaded-src"]!==a&&(e["data-loaded-src"]=a,("decode"in e?e.decode():Promise.resolve()).catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==r?void 0:r.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let n=!1,i=!1;r.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>n,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{n=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==n?void 0:n.current)&&n.current(e)}}))}function m(e){let[t,r]=o.version.split(".",2),n=parseInt(t,10),i=parseInt(r,10);return n>18||18===n&&i>=3?{fetchPriority:e}:{fetchpriority:e}}"undefined"==typeof window&&(globalThis.__NEXT_IMAGE_IMPORTED=!0);let y=(0,o.forwardRef)((e,t)=>{let{src:r,srcSet:n,sizes:i,height:a,width:l,decoding:c,className:u,style:h,fetchPriority:d,placeholder:p,loading:f,unoptimized:y,fill:b,onLoadRef:v,onLoadingCompleteRef:w,setBlurComplete:E,setShowAltText:S,sizesInput:A,onLoad:I,onError:_,...T}=e;return(0,s.jsx)("img",{...T,...m(d),loading:f,width:l,height:a,decoding:c,"data-nimg":b?"fill":"1",className:u,style:h,sizes:i,srcSet:n,src:r,ref:(0,o.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(_&&(e.src=e.src),e.complete&&g(e,p,v,w,E,y,A))},[r,p,v,w,E,_,y,A,t]),onLoad:e=>{g(e.currentTarget,p,v,w,E,y,A)},onError:e=>{S(!0),"empty"!==p&&E(!0),_&&_(e)}})});function b(e){let{isAppRouter:t,imgAttributes:r}=e,n={as:"image",imageSrcSet:r.srcSet,imageSizes:r.sizes,crossOrigin:r.crossOrigin,referrerPolicy:r.referrerPolicy,...m(r.fetchPriority)};return t&&a.default.preload?(a.default.preload(r.src,n),null):(0,s.jsx)(l.default,{children:(0,s.jsx)("link",{rel:"preload",href:r.srcSet?void 0:r.src,...n},"__nimg-"+r.src+r.srcSet+r.sizes)})}let v=(0,o.forwardRef)((e,t)=>{let r=(0,o.useContext)(d.RouterContext),n=(0,o.useContext)(h.ImageConfigContext),i=(0,o.useMemo)(()=>{let e=f||n||u.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),r=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:r}},[n]),{onLoad:a,onLoadingComplete:l}=e,g=(0,o.useRef)(a);(0,o.useEffect)(()=>{g.current=a},[a]);let m=(0,o.useRef)(l);(0,o.useEffect)(()=>{m.current=l},[l]);let[v,w]=(0,o.useState)(!1),[E,S]=(0,o.useState)(!1),{props:A,meta:I}=(0,c.getImgProps)(e,{defaultLoader:p.default,imgConf:i,blurComplete:v,showAltText:E});return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(y,{...A,unoptimized:I.unoptimized,placeholder:I.placeholder,fill:I.fill,onLoadRef:g,onLoadingCompleteRef:m,setBlurComplete:w,setShowAltText:S,sizesInput:e.sizes,ref:t}),I.priority?(0,s.jsx)(b,{isAppRouter:!r,imgAttributes:A}):null]})});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},82901:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return n}});let n=r(99920)._(r(2265)).default.createContext({})},40687:function(e,t){"use strict";function r(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return r}})},80497:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return a}}),r(72301);let n=r(51564),i=r(7103);function s(e){return void 0!==e.default}function o(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function a(e,t){var r;let a,l,c,{src:u,sizes:h,unoptimized:d=!1,priority:p=!1,loading:f,className:g,quality:m,width:y,height:b,fill:v=!1,style:w,overrideSrc:E,onLoad:S,onLoadingComplete:A,placeholder:I="empty",blurDataURL:_,fetchPriority:T,layout:C,objectFit:R,objectPosition:k,lazyBoundary:P,lazyRoot:D,...B}=e,{imgConf:N,showAltText:L,blurComplete:x,defaultLoader:O}=t,M=N||i.imageConfigDefault;if("allSizes"in M)a=M;else{let e=[...M.deviceSizes,...M.imageSizes].sort((e,t)=>e-t),t=M.deviceSizes.sort((e,t)=>e-t);a={...M,allSizes:e,deviceSizes:t}}if(void 0===O)throw Error("images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config");let U=B.loader||O;delete B.loader,delete B.srcSet;let F="__next_img_default"in U;if(F){if("custom"===a.loader)throw Error('Image with src "'+u+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=U;U=t=>{let{config:r,...n}=t;return e(n)}}if(C){"fill"===C&&(v=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[C];e&&(w={...w,...e});let t={responsive:"100vw",fill:"100vw"}[C];t&&!h&&(h=t)}let K="",V=o(y),H=o(b);if("object"==typeof(r=u)&&(s(r)||void 0!==r.src)){let e=s(u)?u.default:u;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(l=e.blurWidth,c=e.blurHeight,_=_||e.blurDataURL,K=e.src,!v){if(V||H){if(V&&!H){let t=V/e.width;H=Math.round(e.height*t)}else if(!V&&H){let t=H/e.height;V=Math.round(e.width*t)}}else V=e.width,H=e.height}}let $=!p&&("lazy"===f||void 0===f);(!(u="string"==typeof u?u:K)||u.startsWith("data:")||u.startsWith("blob:"))&&(d=!0,$=!1),a.unoptimized&&(d=!0),F&&u.endsWith(".svg")&&!a.dangerouslyAllowSVG&&(d=!0),p&&(T="high");let q=o(m),z=Object.assign(v?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:R,objectPosition:k}:{},L?{}:{color:"transparent"},w),j=x||"empty"===I?null:"blur"===I?'url("data:image/svg+xml;charset=utf-8,'+(0,n.getImageBlurSvg)({widthInt:V,heightInt:H,blurWidth:l,blurHeight:c,blurDataURL:_||"",objectFit:z.objectFit})+'")':'url("'+I+'")',G=j?{backgroundSize:z.objectFit||"cover",backgroundPosition:z.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:j}:{},W=function(e){let{config:t,src:r,unoptimized:n,width:i,quality:s,sizes:o,loader:a}=e;if(n)return{src:r,srcSet:void 0,sizes:void 0};let{widths:l,kind:c}=function(e,t,r){let{deviceSizes:n,allSizes:i}=e;if(r){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let n;n=e.exec(r);n)t.push(parseInt(n[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=n[0]*e),kind:"w"}}return{widths:i,kind:"w"}}return"number"!=typeof t?{widths:n,kind:"w"}:{widths:[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))],kind:"x"}}(t,i,o),u=l.length-1;return{sizes:o||"w"!==c?o:"100vw",srcSet:l.map((e,n)=>a({config:t,src:r,quality:s,width:e})+" "+("w"===c?e:n+1)+c).join(", "),src:a({config:t,src:r,quality:s,width:l[u]})}}({config:a,src:u,unoptimized:d,width:V,quality:q,sizes:h,loader:U});return{props:{...B,loading:$?"lazy":f,fetchPriority:T,width:V,height:H,decoding:"async",className:g,style:{...z,...G},sizes:W.sizes,srcSet:W.srcSet,src:E||W.src},meta:{unoptimized:d,priority:p,placeholder:I,fill:v}}}},28321:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return g},defaultHead:function(){return h}});let n=r(99920),i=r(41452),s=r(57437),o=i._(r(2265)),a=n._(r(65960)),l=r(82901),c=r(36590),u=r(40687);function h(e){void 0===e&&(e=!1);let t=[(0,s.jsx)("meta",{charSet:"utf-8"})];return e||t.push((0,s.jsx)("meta",{name:"viewport",content:"width=device-width"})),t}function d(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(72301);let p=["name","httpEquiv","charSet","itemProp"];function f(e,t){let{inAmpMode:r}=t;return e.reduce(d,[]).reverse().concat(h(r).reverse()).filter(function(){let e=new Set,t=new Set,r=new Set,n={};return i=>{let s=!0,o=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){o=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?s=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?s=!1:t.add(i.type);break;case"meta":for(let e=0,t=p.length;e{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:n})})}let g=function(e){let{children:t}=e,r=(0,o.useContext)(l.AmpStateContext),n=(0,o.useContext)(c.HeadManagerContext);return(0,s.jsx)(a.default,{reduceComponentsToState:f,headManager:n,inAmpMode:(0,u.isInAmpMode)(r),children:t})};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},51564:function(e,t){"use strict";function r(e){let{widthInt:t,heightInt:r,blurWidth:n,blurHeight:i,blurDataURL:s,objectFit:o}=e,a=n?40*n:t,l=i?40*i:r,c=a&&l?"viewBox='0 0 "+a+" "+l+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+c+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(c?"none":"contain"===o?"xMidYMid":"cover"===o?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+s+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return r}})},93938:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return s}});let n=r(99920)._(r(2265)),i=r(7103),s=n.default.createContext(i.imageConfigDefault)},7103:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},61669:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return l},getImageProps:function(){return a}});let n=r(99920),i=r(80497),s=r(38173),o=n._(r(21241));function a(e){let{props:t}=(0,i.getImgProps)(e,{defaultLoader:o.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,r]of Object.entries(t))void 0===r&&delete t[e];return{props:t}}let l=s.Image},21241:function(e,t){"use strict";function r(e){let{config:t,src:r,width:n,quality:i}=e;return t.path+"?url="+encodeURIComponent(r)+"&w="+n+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}}),r.__next_img_default=!0;let n=r},60291:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RouterContext",{enumerable:!0,get:function(){return n}});let n=r(99920)._(r(2265)).default.createContext(null)},65960:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let n=r(2265),i="undefined"==typeof window,s=i?()=>{}:n.useLayoutEffect,o=i?()=>{}:n.useEffect;function a(e){let{headManager:t,reduceComponentsToState:r}=e;function a(){if(t&&t.mountedInstances){let i=n.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(r(i,e))}}if(i){var l;null==t||null==(l=t.mountedInstances)||l.add(e.children),a()}return s(()=>{var r;return null==t||null==(r=t.mountedInstances)||r.add(e.children),()=>{var r;null==t||null==(r=t.mountedInstances)||r.delete(e.children)}}),s(()=>(t&&(t._pendingUpdate=a),()=>{t&&(t._pendingUpdate=a)})),o(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},98258:function(e,t,r){var n,i,s,o,a,l=r(95482);function c(e,t){l.cipher.registerAlgorithm(e,function(){return new l.aes.Algorithm(e,t)})}r(62474),r(39648),r(77939),e.exports=l.aes=l.aes||{},l.aes.startEncrypting=function(e,t,r,n){var i=f({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},l.aes.createEncryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!1,mode:t})},l.aes.startDecrypting=function(e,t,r,n){var i=f({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},l.aes.createDecryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!0,mode:t})},l.aes.Algorithm=function(e,t){u||h();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return p(r._w,e,t,!1)},decrypt:function(e,t){return p(r._w,e,t,!0)}}}),r._init=!1},l.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"==typeof r&&(16===r.length||24===r.length||32===r.length))r=l.util.createBuffer(r);else if(l.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=l.util.createBuffer();for(var n=0;n>>=2;for(var n=0;n>8^255&h^99,n[g]=h,i[h]=g,d=e[h],r=e[g],l=e[r],c=e[l],p=d<<24^h<<16^h<<8^(h^d),f=(r^l^c)<<24^(g^c)<<16^(g^l^c)<<8^(g^r^c);for(var y=0;y<4;++y)o[y][g]=p,a[y][h]=f,p=p<<24|p>>>8,f=f<<24|f>>>8;0===g?g=m=1:(g=r^e[e[e[r^c]]],m^=e[e[m]])}}function d(e,t){for(var r,i=e.slice(0),o=1,l=i.length,c=4*(l+6+1),u=l;u>>16&255]<<24^n[r>>>8&255]<<16^n[255&r]<<8^n[r>>>24]^s[o]<<24,o++):l>6&&u%l==4&&(r=n[r>>>24]<<24^n[r>>>16&255]<<16^n[r>>>8&255]<<8^n[255&r]),i[u]=i[u-l]^r;if(t){var h,d=a[0],p=a[1],f=a[2],g=a[3],m=i.slice(0);c=i.length;for(var u=0,y=c-4;u>>24]]^p[n[h>>>16&255]]^f[n[h>>>8&255]]^g[n[255&h]];i=m}return i}function p(e,t,r,s){var l,c,u,h,d,p,f,g,m,y,b,v,w=e.length/4-1;s?(l=a[0],c=a[1],u=a[2],h=a[3],d=i):(l=o[0],c=o[1],u=o[2],h=o[3],d=n),p=t[0]^e[0],f=t[s?3:1]^e[1],g=t[2]^e[2],m=t[s?1:3]^e[3];for(var E=3,S=1;S>>24]^c[f>>>16&255]^u[g>>>8&255]^h[255&m]^e[++E],b=l[f>>>24]^c[g>>>16&255]^u[m>>>8&255]^h[255&p]^e[++E],v=l[g>>>24]^c[m>>>16&255]^u[p>>>8&255]^h[255&f]^e[++E],m=l[m>>>24]^c[p>>>16&255]^u[f>>>8&255]^h[255&g]^e[++E],p=y,f=b,g=v;r[0]=d[p>>>24]<<24^d[f>>>16&255]<<16^d[g>>>8&255]<<8^d[255&m]^e[++E],r[s?3:1]=d[f>>>24]<<24^d[g>>>16&255]<<16^d[m>>>8&255]<<8^d[255&p]^e[++E],r[2]=d[g>>>24]<<24^d[m>>>16&255]<<16^d[p>>>8&255]<<8^d[255&f]^e[++E],r[s?1:3]=d[m>>>24]<<24^d[p>>>16&255]<<16^d[f>>>8&255]<<8^d[255&g]^e[++E]}function f(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),n=(t=e.decrypt?l.cipher.createDecipher(r,e.key):l.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof l.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,n.call(t,r)},t}},66163:function(e,t,r){var n=r(95482);r(77939),r(72822);var i=e.exports=n.asn1=n.asn1||{};function s(e,t,r){if(r>t){var n=Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,s,o){if(n.util.isArray(s)){for(var a=[],l=0;lr){if(a.strict){var g=Error("Too few bytes to read ASN.1 value.");throw g.available=t.length(),g.remaining=r,g.requested=f,g}f=r}var m=(32&h)==32;if(m){if(c=[],void 0===f)for(;;){if(s(t,r,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),r-=2;break}l=t.length(),c.push(e(t,r,n+1,a)),r-=l-t.length()}else for(;f>0;)l=t.length(),c.push(e(t,f,n+1,a)),r-=l-t.length(),f-=l-t.length()}if(void 0===c&&d===i.Class.UNIVERSAL&&p===i.Type.BITSTRING&&(u=t.bytes(f)),void 0===c&&a.decodeBitStrings&&d===i.Class.UNIVERSAL&&p===i.Type.BITSTRING&&f>1){var y=t.read,b=r,v=0;if(p===i.Type.BITSTRING&&(s(t,r,1),v=t.getByte(),r--),0===v)try{l=t.length();var w=e(t,r,n+1,{strict:!0,decodeBitStrings:!0}),E=l-t.length();r-=E,p==i.Type.BITSTRING&&E++;var S=w.tagClass;E===f&&(S===i.Class.UNIVERSAL||S===i.Class.CONTEXT_SPECIFIC)&&(c=[w])}catch(e){}void 0===c&&(t.read=y,r=b)}if(void 0===c){if(void 0===f){if(a.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");f=r}if(p===i.Type.BMPSTRING)for(c="";f>0;f-=2)s(t,r,2),c+=String.fromCharCode(t.getInt16()),r-=2;else c=t.getBytes(f),r-=f}var A=void 0===u?null:{bitStringContents:u};return i.create(d,p,m,c,A)}(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var l=Error("Unparsed DER bytes remain after ASN.1 parsing.");throw l.byteCount=r,l.remaining=e.length(),l}return a},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,s=n.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=i.equals(e,e.original))),o)s.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:s.putByte(0);for(var a=0;a1&&(0===e.value.charCodeAt(0)&&(128&e.value.charCodeAt(1))==0||255===e.value.charCodeAt(0)&&(128&e.value.charCodeAt(1))==128)?s.putBytes(e.value.substr(1)):s.putBytes(e.value);if(t.putByte(r),127>=s.length())t.putByte(127&s.length());else{var l=s.length(),c="";do c+=String.fromCharCode(255&l),l>>>=8;while(l>0);t.putByte(128|c.length);for(var a=c.length-1;a>=0;--a)t.putByte(c.charCodeAt(a))}return t.putBuffer(s),t},i.oidToDer=function(e){var t,r,i,s,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var l=2;l>>=7,t||(s|=128),r.push(s),t=!1;while(i>0);for(var c=r.length-1;c>=0;--c)a.putByte(r[c])}return a},i.derToOid=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t,r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)r=e.getByte(),i<<=7,128&r?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),s=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var l=e.charAt(10),c=10;"+"!==l&&"-"!==l&&(a=parseInt(e.substr(10,2),10),c+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,0),c&&("+"===(l=e.charAt(c))||"-"===l)){var u=60*parseInt(e.substr(c+1,2),10)+parseInt(e.substr(c+4,2),10);u*=6e4,"+"===l?t.setTime(+t-u):t.setTime(+t+u)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),l=0,c=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);return("+"===d||"-"===d)&&(c=(60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10))*6e4,"+"===d&&(c*=-1),u=!0),"."===e.charAt(14)&&(l=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,l),t.setTime(+t+c)):(t.setFullYear(r,n,i),t.setHours(s,o,a,l)),t},i.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,s){var o=!1;if((e.tagClass===t.tagClass||void 0===t.tagClass)&&(e.type===t.type||void 0===t.type)){if(e.constructed===t.constructed||void 0===t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,l=0;o&&l0&&(s+="\n");for(var o="",l=0;l1?s+="0x"+n.util.bytesToHex(e.value.slice(1)):s+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?s+=" (1 unused bit shown)":d>1&&(s+=" ("+d+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(s+="("+e.value+") "),s+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{s+=n.util.decodeUtf8(e.value)}catch(t){if("URI malformed"===t.message)s+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)";else throw t}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?s+=e.value:a.test(e.value)?s+="0x"+n.util.bytesToHex(e.value):0===e.value.length?s+="[null]":s+=e.value}return s}},16994:function(e,t,r){var n=r(62678).Buffer,i={};e.exports=i;var s={};i.encode=function(e,t,r){if("string"!=typeof t)throw TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!=typeof r)throw TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),a=[0];for(i=0;i0;)a.push(c%s),c=c/s|0}for(i=0;0===e[i]&&i=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),s=[0];for(r=0;r0;)s.push(a%n),a=a/n|0}var l="";for(r=0;0===e.at(r)&&r=0;--r)l+=t[s[r]];return l}(e,t);if(r){var u=RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},i.decode=function(e,t){if("string"!=typeof e)throw TypeError('"input" must be a string.');if("string"!=typeof t)throw TypeError('"alphabet" must be a string.');var r=s[t];if(!r){r=s[t]=[];for(var i=0;i>=8;for(;h>0;)l.push(255&h),h>>=8}for(var d=0;e[d]===a&&d4){var r=e;e=n.util.createBuffer();for(var i=0;i0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=s(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw Error("Invalid IV parameter.")},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)e.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)e.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)e.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw Error("Authentication tag does not match tag length.");this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var s=t.length()%this.blockSize;for(s&&t.fillWithByte(0,this.blockSize-s),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),o(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),o(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>(7-r%8)*4&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,s=Array(i),o=0;o>>1,i=Array(r);i[n]=e.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s8?3:1,y=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],v=0,w=0;w>>4^S)&252645135,S^=t,E^=t<<4,t=(S>>>-16^E)&65535,E^=t,S^=t<<-16,t=(E>>>2^S)&858993459,S^=t,E^=t<<2,t=(S>>>-16^E)&65535,E^=t,S^=t<<-16,t=(E>>>1^S)&1431655765,S^=t,E^=t<<1,t=(S>>>8^E)&16711935,E^=t,S^=t<<8,t=(E>>>1^S)&1431655765,S^=t,E^=t<<1,t=E<<8|S>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var A=0;A>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),S&=-15;var I=r[(E&=-15)>>>28]|n[E>>>24&15]|i[E>>>20&15]|s[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|l[E>>>4&15],_=c[S>>>28]|u[S>>>24&15]|h[S>>>20&15]|d[S>>>16&15]|p[S>>>12&15]|f[S>>>8&15]|g[S>>>4&15];t=(_>>>16^I)&65535,y[v++]=I^t,y[v++]=_^t<<16}}return y}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],l=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],c=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function p(e,t,r,n){var i,p,f=32===e.length?3:9;i=3===f?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],m=t[1];p=(g>>>4^m)&252645135,m^=p,g^=p<<4,p=(g>>>16^m)&65535,m^=p,g^=p<<16,p=(m>>>2^g)&858993459,g^=p,m^=p<<2,p=(m>>>8^g)&16711935,g^=p,m^=p<<8,p=(g>>>1^m)&1431655765,m^=p,g^=p<<1,g=g<<1|g>>>31,m=m<<1|m>>>31;for(var y=0;y>>4|m<<28)^e[w+1];p=g,g=m,m=p^(o[E>>>24&63]|l[E>>>16&63]|u[E>>>8&63]|d[63&E]|s[S>>>24&63]|a[S>>>16&63]|c[S>>>8&63]|h[63&S])}p=g,g=m,m=p}p=((g=g>>>1|g<<31)>>>1^(m=m>>>1|m<<31))&1431655765,m^=p,g^=p<<1,p=(m>>>8^g)&16711935,g^=p,m^=p<<8,p=(m>>>2^g)&858993459,g^=p,m^=p<<2,p=(g>>>16^m)&65535,m^=p,g^=p<<16,p=(g>>>4^m)&252645135,m^=p,g^=p<<4,r[0]=g,r[1]=m}function f(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},95482:function(e){e.exports={options:{usePureJavaScript:!1}}},44215:function(e,t,r){var n=r(95482);r(3654),r(77939),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,s={};return s.start=function(s,o){if(null!==s){if("string"==typeof s){if((s=s.toLowerCase())in n.md.algorithms)t=n.md.algorithms[s].create();else throw Error('Unknown hash algorithm "'+s+'"')}else t=s}if(null===o)o=e;else{if("string"==typeof o)o=n.util.createBuffer(o);else if(n.util.isArray(o)){var a=o;o=n.util.createBuffer();for(var l=0;lt.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),c=o.length();for(var l=0;l>14;--s>=0;){var l=16383&this.data[e],c=this.data[e++]>>14,u=a*l+c*o;i=((l=o*l+((16383&u)<<14)+r.data[n]+i)>>28)+(u>>14)+a*c,r.data[n++]=268435455&l}return i}e.exports=o.jsbn=o.jsbn||{},o.jsbn.BigInteger=a,"undefined"==typeof navigator?(a.prototype.am=c,n=28):"Microsoft Internet Explorer"==navigator.appName?(a.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var l=32767&this.data[e],c=this.data[e++]>>15,u=a*l+c*o;i=((l=o*l+((32767&u)<<15)+r.data[n]+(1073741823&i))>>>30)+(u>>>15)+a*c+(i>>>30),r.data[n++]=1073741823&l}return i},n=30):"Netscape"!=navigator.appName?(a.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this.data[e++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=67108863&o}return i},n=26):(a.prototype.am=c,n=28),a.prototype.DB=n,a.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function m(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},m.prototype.convert=function(e){var t=l();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(a.ZERO)>0&&this.m.subTo(t,t),t},m.prototype.revert=function(e){var t=l();return e.copyTo(t),this.reduce(t),t},m.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},m.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},m.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},a.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},a.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},a.prototype.fromString=function(e,t){if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else if(4==t)r=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var r,n=e.length,i=!1,s=0;--n>=0;){var o=8==r?255&e[n]:d(e,n);if(o<0){"-"==e.charAt(n)&&(i=!0);continue}i=!1,0==s?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB)}8==r&&(128&e[0])!=0&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},a.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},a.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+o+1]=this.data[r]>>i|a,a=(this.data[r]&s)<=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},a.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t){t.t=0;return}var n=e%this.DB,i=this.DB-n,s=(1<>n;for(var o=r+1;o>n;n>0&&(t.data[this.t-r-1]|=(this.s&s)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},a.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},a.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(u,s),i.lShiftTo(u,r)):(n.copyTo(s),i.copyTo(r));var h=s.t,d=s.data[h-1];if(0!=d){var p=d*(1<1?s.data[h-2]>>this.F2:0),g=this.FV/p,m=(1<=0&&(r.data[r.t++]=1,r.subTo(w,r)),a.ONE.dlShiftTo(h,w),w.subTo(s,s);s.t=0;){var E=r.data[--b]==d?this.DM:Math.floor(r.data[b]*g+(r.data[b-1]+y)*m);if((r.data[b]+=s.am(0,E,r,v,0,h))0&&r.rShiftTo(u,r),o<0&&a.ZERO.subTo(r,r)}}},a.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if((1&e)==0)return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},a.prototype.isEven=function(){return(this.t>0?1&this.data[0]:this.s)==0},a.prototype.exp=function(e,t){if(e>4294967295||e<1)return a.ONE;var r=l(),n=l(),i=t.convert(this),s=f(e)-1;for(i.copyTo(r);--s>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var o=r;r=n,n=o}return t.revert(r)},a.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var t,r,n=(1<0)for(a>a)>0&&(i=!0,s=h(r));o>=0;)a>(a+=this.DB-t):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=h(r));return i?s:"0"},a.prototype.negate=function(){var e=l();return a.ZERO.subTo(this,e),e},a.prototype.abs=function(){return this.s<0?this.negate():this},a.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},a.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+f(this.data[this.t-1]^this.s&this.DM)},a.prototype.mod=function(e){var t=l();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(a.ZERO)>0&&e.subTo(t,t),t},a.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new m(t),this.exp(e,r)},a.ZERO=p(0),a.ONE=p(1),E.prototype.convert=S,E.prototype.revert=S,E.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},E.prototype.sqrTo=function(e,t){e.squareTo(t)},A.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(0>e.compareTo(this.m))return e;var t=l();return e.copyTo(t),this.reduce(t),t},A.prototype.revert=function(e){return e},A.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);0>e.compareTo(this.r2);)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var I=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],_=67108864/I[I.length-1];a.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},a.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=p(r),i=l(),s=l(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(e).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(e)+o},a.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,s=0,o=0,l=0;l=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),i&&a.ZERO.subTo(this,this)},a.prototype.fromNumber=function(e,t,r){if("number"==typeof t){if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(a.ONE.shiftLeft(e-1),b,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(a.ONE.shiftLeft(e-1),this)}else{var n=[],i=7&e;n.length=(e>>3)+1,t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},a.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},a.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},a.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0){if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e}return r},a.prototype.millerRabin=function(e){var t,r=this.subtract(a.ONE),n=r.getLowestSetBit();if(n<=0)return!1;for(var i=r.shiftRight(n),s={nextBytes:function(e){for(var t=0;t=t.compareTo(a.ONE)||t.compareTo(r)>=0);var l=t.modPow(i,this);if(0!=l.compareTo(a.ONE)&&0!=l.compareTo(r)){for(var c=1;c++>24},a.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},a.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},a.prototype.toByteArray=function(){var e=this.t,t=[];t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?r=(this.data[e]&(1<>(n+=this.DB-8):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),(128&r)!=0&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},a.prototype.equals=function(e){return 0==this.compareTo(e)},a.prototype.min=function(e){return 0>this.compareTo(e)?this:e},a.prototype.max=function(e){return this.compareTo(e)>0?this:e},a.prototype.and=function(e){var t=l();return this.bitwiseTo(e,y,t),t},a.prototype.or=function(e){var t=l();return this.bitwiseTo(e,b,t),t},a.prototype.xor=function(e){var t=l();return this.bitwiseTo(e,v,t),t},a.prototype.andNot=function(e){var t=l();return this.bitwiseTo(e,w,t),t},a.prototype.not=function(){for(var e=l(),t=0;t>=16,t+=16),(255&e)==0&&(e>>=8,t+=8),(15&e)==0&&(e>>=4,t+=4),(3&e)==0&&(e>>=2,t+=2),(1&e)==0&&++t,t}(this.data[e]);return this.s<0?this.t*this.DB:-1},a.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r=this.t?0!=this.s:(this.data[t]&1<1){var h=l();for(n.sqrTo(o[1],h);a<=u;)o[a]=l(),n.mulTo(h,o[a-2],o[a]),a+=2}var d,y,b=e.t-1,v=!0,w=l();for(i=f(e.data[b])-1;b>=0;){for(i>=c?d=e.data[b]>>i-c&u:(d=(e.data[b]&(1<0&&(d|=e.data[b-1]>>this.DB+i-c)),a=r;(1&d)==0;)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--b),v)o[d].copyTo(s),v=!1;else{for(;a>1;)n.sqrTo(s,w),n.sqrTo(w,s),a-=2;a>0?n.sqrTo(s,w):(y=s,s=w,w=y),n.mulTo(w,o[d],s)}for(;b>=0&&(e.data[b]&1<=0?(r.subTo(n,r),t&&i.subTo(o,i),s.subTo(l,s)):(n.subTo(r,n),t&&o.subTo(i,o),l.subTo(s,l))}return 0!=n.compareTo(a.ONE)?a.ZERO:l.compareTo(e)>=0?l.subtract(e):0>l.signum()&&(l.addTo(e,l),0>l.signum())?l.add(e):l},a.prototype.pow=function(e){return this.exp(e,new E)},a.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(0>t.compareTo(r)){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},a.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=I[I.length-1]){for(t=0;t=0;l--)k>>=8,k+=_.at(l)+R.at(l),R.setAt(l,255&k);C.putBuffer(R)}w=C,h.putBuffer(A)}return h.truncate(h.length()-s),h},o.pbe.getCipher=function(e,t,r){switch(e){case o.oids.pkcs5PBES2:return o.pbe.getCipherForPBES2(e,t,r);case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case o.oids["pbewithSHAAnd40BitRC2-CBC"]:return o.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},o.pbe.getCipherForPBES2=function(e,t,r){var i,a,l={},u=[];if(!s.validate(t,c,l,u)){var h=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw h.errors=u,h}if((e=s.derToOid(l.kdfOid))!==o.oids.pkcs5PBKDF2){var h=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw h.oid=e,h.supportedOids=["pkcs5PBKDF2"],h}if((e=s.derToOid(l.encOid))!==o.oids["aes128-CBC"]&&e!==o.oids["aes192-CBC"]&&e!==o.oids["aes256-CBC"]&&e!==o.oids["des-EDE3-CBC"]&&e!==o.oids.desCBC){var h=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw h.oid=e,h.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],h}var p=l.kdfSalt,f=n.util.createBuffer(l.kdfIterationCount);switch(f=f.getInt(f.length()<<3),o.oids[e]){case"aes128-CBC":i=16,a=n.aes.createDecryptionCipher;break;case"aes192-CBC":i=24,a=n.aes.createDecryptionCipher;break;case"aes256-CBC":i=32,a=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":i=24,a=n.des.createDecryptionCipher;break;case"desCBC":i=8,a=n.des.createDecryptionCipher}var g=d(l.prfOid),m=n.pkcs5.pbkdf2(r,p,f,i,g),y=l.encIv,b=a(m);return b.start(y),b},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var i,a,l,c={},h=[];if(!s.validate(t,u,c,h)){var p=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw p.errors=h,p}var f=n.util.createBuffer(c.salt),g=n.util.createBuffer(c.iterations);switch(g=g.getInt(g.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:i=24,a=8,l=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:i=5,a=8,l=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var p=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw p.oid=e,p}var m=d(c.prfOid),y=o.pbe.generatePkcs12Key(r,f,1,g,i,m);return m.start(),l(y,o.pbe.generatePkcs12Key(r,f,2,g,a,m))},o.pbe.opensslDeriveBytes=function(e,t,r,i){if(null==i){if(!("md5"in n.md))throw Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var s=[h(i,e+t)],o=16,a=1;o4||!a||"sha1"===a))return("string"!=typeof a&&(a="sha1"),e=i.from(e,"binary"),t=i.from(t,"binary"),l)?4===n.pbkdf2Sync.length?n.pbkdf2(e,t,r,o,function(e,t){if(e)return l(e);l(null,t.toString("binary"))}):n.pbkdf2(e,t,r,o,a,function(e,t){if(e)return l(e);l(null,t.toString("binary"))}):4===n.pbkdf2Sync.length?n.pbkdf2Sync(e,t,r,o).toString("binary"):n.pbkdf2Sync(e,t,r,o,a).toString("binary");if(null==a&&(a="sha1"),"string"==typeof a){if(!(a in s.md.algorithms))throw Error("Unknown hash algorithm: "+a);a=s.md[a].create()}var c=a.digestLength;if(o>4294967295*c){var u=Error("Derived key is too long.");if(l)return l(u);throw u}var h=Math.ceil(o/c),d=o-(h-1)*c,p=s.hmac.create();p.start(a,e);var f="";if(!l){for(var g=1;g<=h;++g){p.start(null,null),p.update(t),p.update(s.util.int32ToBytes(g)),y=v=p.digest().getBytes();for(var m=2;m<=r;++m)p.start(null,null),p.update(v),b=p.digest().getBytes(),y=s.util.xorBytes(y,b,c),v=b;f+=gh)return l(null,f);p.start(null,null),p.update(t),p.update(s.util.int32ToBytes(g)),y=v=p.digest().getBytes(),m=2,function t(){if(m<=r)return p.start(null,null),p.update(v),b=p.digest().getBytes(),y=s.util.xorBytes(y,b,c),v=b,++m,s.util.setImmediate(t);f+=g65&&-1!==o){var a=t[o];","===a?(++o,t=t.substr(0,o)+"\r\n "+t.substr(o)):t=t.substr(0,o)+"\r\n"+a+t.substr(o+1),s=i-o-1,o=-1,++i}else(" "===t[i]||" "===t[i]||","===t[i])&&(o=i);return t}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=s(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=s(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=s(r)),e.headers)for(var o=0;o>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){"string"==typeof r?(i=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(l=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),l||(l=a);var i,o,a,l,c=Math.ceil(e.n.bitLength()/8),u=c-2*a.digestLength-2;if(t.length>u){var h=Error("RSAES-OAEP input message length is too long.");throw h.length=t.length,h.maxLength=u,h}i||(i=""),a.update(i,"raw");for(var d=a.digest(),p="",f=u-t.length,g=0;gr&&(t=l(r,s)),t.isProbablePrime(a))return u(null,t);t.dAddOffset(i[o++%8],0)}while(c<0||+new Date-he&&(o=l(e,t));var f=o.toString(16);i.target.postMessage({hex:f,workLoad:u}),o.dAddOffset(h,0)}}}p()}(e,s,o,c):a(e,s,o,c);throw Error("Invalid prime generation algorithm: "+u.name)}}()},35824:function(e,t,r){var n=r(24112),i=r(95482);r(77939);var s=null;!i.util.isNodejs||i.options.usePureJavaScript||n.versions["node-webkit"]||(s=r(25819)),(e.exports=i.prng=i.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,n=Array(32),o=0;o<32;++o)n[o]=r.create();function a(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r==0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function l(e){var t=null,r=i.util.globalScope,n=r.crypto||r.msCrypto;n&&n.getRandomValues&&(t=function(e){return n.getRandomValues(e)});var s=i.util.createBuffer();if(t)for(;s.length()>16)))<<16)+(l>>15))))+(c>>31));for(var a=0;a<3;++a)u=h>>>(a<<3)^Math.floor(256*Math.random()),s.putByte(255&u)}return s.getBytes(e)}return t.pools=n,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var n=t.plugin.cipher,s=t.plugin.increment,o=t.plugin.formatKey,l=t.plugin.formatSeed,c=i.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(c.length()>=e)return r(null,c.getBytes(e));if(t.generated>1048575&&(t.key=null),null===t.key)return i.util.nextTick(function(){(function(e){if(t.pools[0].messageLength>=32)return a(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,function(r,n){if(r)return e(r);t.collect(n),a(),e()})})(u)});var d=n(t.key,t.seed);t.generated+=d.length,c.putBytes(d),t.key=o(n(t.key,s(t.seed))),t.seed=l(n(t.key,t.seed)),i.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,n=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var l=i.util.createBuffer();l.length()1048575&&(t.key=null),null===t.key&&function(){if(t.pools[0].messageLength>=32)return a();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),a()}();var c=r(t.key,t.seed);t.generated+=c.length,l.putBytes(c),t.key=s(r(t.key,n(t.seed))),t.seed=o(r(t.key,t.seed))}return l.getBytes(e)},s?(t.seedFile=function(e,t){s.randomBytes(e,function(e,r){if(e)return t(e);t(null,r.toString())})},t.seedFileSync=function(e){return s.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,l(e))}catch(e){t(e)}},t.seedFileSync=l),t.collect=function(e){for(var r=e.length,n=0;n>i&255);t.collect(n)},t.registerWorker=function(e){e===self?t.seedFile=function(e,t){self.addEventListener("message",function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))}),self.postMessage({forge:{prng:{needed:e}}})}:e.addEventListener("message",function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})})})},t}},20576:function(e,t,r){var n=r(95482);r(98258),r(22541),r(35824),r(77939),function(){if(n.random&&n.random.getBytes){e.exports=n.random;return}!function(t){var r={},i=[,,,,],s=n.util.createBuffer();function o(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=[,,,,])[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=[,,,,])[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),s.putInt32(i[0]),s.putInt32(i[1]),s.putInt32(i[2]),s.putInt32(i[3]),s.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),l=null,c=n.util.globalScope,u=c.crypto||c.msCrypto;if(u&&u.getRandomValues&&(l=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!l){if("undefined"==typeof window||window.document,a.collectInt(+new Date,32),"undefined"!=typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(e){}a.collect(h),h=null}t&&(t().mousemove(function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)}),t().keypress(function(e){a.collectInt(e.charCode,8)}))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=o,e.exports=n.random}("undefined"!=typeof jQuery?jQuery:null)}()},62068:function(e,t,r){var n=r(95482);r(77939);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s=[1,2,3,5];e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"==typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,s=e,o=e.length(),a=t,l=Math.ceil(a/8);for(r=o;r<128;r++)s.putByte(i[s.at(r-1)+s.at(r-o)&255]);for(s.setAt(128-l,i[s.at(128-l)&255>>(7&a)]),r=127-l;r>=0;r--)s.setAt(r,i[s.at(r+1)^s.at(r+l)]);return s};var o=function(e,t,r){var i,o,a,l,c=!1,u=null,h=null,d=null,p=[];for(a=0,e=n.rc2.expandKey(e,t);a<64;a++)p.push(e.getInt16Le());r?(i=function(e){for(a=0;a<4;a++){var t,r;e[a]+=p[l]+(e[(a+3)%4]&e[(a+2)%4])+(~e[(a+3)%4]&e[(a+1)%4]),e[a]=(t=e[a])<<(r=s[a])&65535|(65535&t)>>16-r,l++}},o=function(e){for(a=0;a<4;a++)e[a]+=p[63&e[(a+3)%4]]}):(i=function(e){for(a=3;a>=0;a--){var t,r;e[a]=(65535&(t=e[a]))>>(r=s[a])|t<<16-r&65535,e[a]-=p[l]+(e[(a+3)%4]&e[(a+2)%4])+(~e[(a+3)%4]&e[(a+1)%4]),l--}},o=function(e){for(a=3;a>=0;a--)e[a]-=p[63&e[(a+3)%4]]});var f=function(e){var t=[];for(a=0;a<4;a++){var n=u.getInt16Le();null!==d&&(r?n^=d.getInt16Le():d.putInt16Le(n)),t.push(65535&n)}l=r?0:63;for(var i=0;i=8;)f([[5,i],[1,o],[6,i],[1,o],[5,i]])},finish:function(e){var t=!0;if(r){if(e)t=e(8,u,!r);else{var n=8===u.length()?8:8-u.length();u.fillWithByte(n,n)}}if(t&&(c=!0,g.update()),!r&&(t=0===u.length())){if(e)t=e(8,h,!r);else{var i=h.length(),s=h.at(i-1);s>i?t=!1:h.truncate(s)}}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return o(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return o(e,t,!1)}},87821:function(e,t,r){var n=r(95482);if(r(66163),r(51275),r(72822),r(36866),r(43365),r(20576),r(77939),void 0===i)var i=n.jsbn.BigInteger;var s=n.util.isNodejs?r(25819):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var l=n.pki,c=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},p=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},f={name:"DigestInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){if(e.algorithm in l.oids)t=l.oids[e.algorithm];else{var t,r=Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}var n=o.oidToDer(t).getBytes(),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);s.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),s.value.push(o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,""));var a=o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),o.toDer(i).getBytes()},m=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do s=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16);while(s.compareTo(t.n)>=0||!s.gcd(t.n).equals(i.ONE));for(var s,o=(e=e.multiply(s.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);0>o.compareTo(a);)o=o.add(t.p);return o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a).multiply(s.modInverse(t.n)).mod(t.n)};function y(e,t,r){var i,s=n.util.createBuffer(),o=Math.ceil(t.n.bitLength()/8);if(e.length>o-11){var a=Error("Message is too long for PKCS#1 v1.5 padding.");throw a.length=e.length,a.max=o-11,a}s.putByte(0),s.putByte(r);var l=o-3-e.length;if(0===r||1===r){i=0===r?0:255;for(var c=0;c0;){for(var u=0,h=n.random.getBytes(l),c=0;c1;){if(255!==o.getByte()){--o.read;break}++c}else if(2===l)for(c=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++c}if(0!==o.getByte()||c!==s-3-o.length())throw Error("Encryption block is invalid.");return o.getBytes()}function v(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&(128&r.charCodeAt(1))==0||255===r.charCodeAt(0)&&(128&r.charCodeAt(1))==128)?r.substr(1):r}function w(e){return n.util.isNodejs&&"function"==typeof s[e]}function E(e){return void 0!==a.globalScope&&"object"==typeof a.globalScope.crypto&&"object"==typeof a.globalScope.crypto.subtle&&"function"==typeof a.globalScope.crypto.subtle[e]}function S(e){return void 0!==a.globalScope&&"object"==typeof a.globalScope.msCrypto&&"object"==typeof a.globalScope.msCrypto.subtle&&"function"==typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i0;)c.putByte(0),--u;return c.putBytes(n.util.hexToBytes(l)),c.getBytes()},l.rsa.decrypt=function(e,t,r,s){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var l=new i(n.util.createBuffer(e).toHex(),16);if(l.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");for(var c=m(l,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(c.length/2);h>0;)u.putByte(0),--h;return(u.putBytes(n.util.hexToBytes(c)),!1!==s)?b(u.getBytes(),t,r):u.getBytes()},l.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var s,o=(r=r||{}).prng||n.random,a=r.algorithm||"PRIMEINC";if("PRIMEINC"===a)(s={algorithm:a,state:0,bits:e,rng:{nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(s.eInt);else throw Error("Invalid key generation algorithm: "+a);return s},l.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r,n=new i(null);n.fromInt(30);for(var s=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||ud?e.pqState=0:e.num.isProbablePrime((h=e.num.bitLength())<=100?27:h<=150?18:h<=200?15:h<=250?12:h<=300?9:h<=350?8:h<=400?7:h<=500?6:h<=600?5:h<=800?4:h<=1250?3:2)?++e.pqState:e.num.dAddOffset(c[s++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)0>e.p.compareTo(e.q)&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:l.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:l.rsa.setPublicKey(e.n,e.e)}}u+=(r=+new Date)-a,a=r}return null!==e.keys},l.rsa.generateKeyPair=function(e,t,r,c){if(1==arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(c=e,e=void 0):2==arguments.length?"number"==typeof e?"function"==typeof t?(c=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,c=t,e=void 0,t=void 0):3==arguments.length&&("number"==typeof t?"function"==typeof r&&(c=r,r=void 0):(c=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t)){if(c){if(w("generateKeyPair"))return s.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(e,t,r){if(e)return c(e);c(null,{privateKey:l.privateKeyFromPem(r),publicKey:l.publicKeyFromPem(t)})});if(E("generateKey")&&E("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)}).then(void 0,function(e){c(e)}).then(function(e){if(e){var t=l.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));c(null,{privateKey:t,publicKey:l.setRsaPublicKey(t.n,t.e)})}});if(S("generateKey")&&S("exportKey")){var u=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);u.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=l.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));c(null,{privateKey:r,publicKey:l.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){c(e)}},u.onerror=function(e){c(e)};return}}else if(w("generateKeyPairSync")){var h=s.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:l.privateKeyFromPem(h.privateKey),publicKey:l.publicKeyFromPem(h.publicKey)}}}var d=l.rsa.createKeyPairGenerationState(e,t,r);if(!c)return l.rsa.stepKeyPairGenerationState(d,0),d.keys;(function(e,t,r){"function"==typeof t&&(r=t,t={});var s={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function o(){a(e.pBits,function(t,n){return t?r(t):(e.p=n,null!==e.q)?c(t,e.q):void a(e.qBits,c)})}function a(e,t){n.prime.generateProbablePrime(e,s,t)}function c(t,n){if(t)return r(t);if(e.q=n,0>e.p.compareTo(e.q)){var s=e.p;e.p=e.q,e.q=s}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)){e.p=null,o();return}if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)){e.q=null,a(e.qBits,c);return}if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE)){e.p=e.q=null,o();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,a(e.qBits,c);return}var u=e.e.modInverse(e.phi);e.keys={privateKey:l.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:l.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(s.prng=t.prng),o()})(d,r,c)},l.setRsaPublicKey=l.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(e,t,i){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return y(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw Error('Unsupported encryption scheme: "'+t+'".');var s=t.encode(e,r,!0);return l.rsa.encrypt(s,r,!0)},r.verify=function(e,t,i,s){"string"==typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===s&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=b(t,r,!0);var i=o.fromDer(t,{parseAllBytes:s._parseAllDigestBytes}),a={},l=[];if(!o.validate(i,f,a,l)){var c=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw c.errors=l,c}var u=o.derToOid(a.algorithmIdentifier);if(!(u===n.oids.md2||u===n.oids.md5||u===n.oids.sha1||u===n.oids.sha224||u===n.oids.sha256||u===n.oids.sha384||u===n.oids.sha512||u===n.oids["sha512-224"]||u===n.oids["sha512-256"])){var c=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw c.oid=u,c}if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:("NONE"===i||"NULL"===i||null===i)&&(i={verify:function(e,t){return e===(t=b(t,r,!0))}});var a=l.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())},r},l.setRsaPrivateKey=l.rsa.setPrivateKey=function(e,t,r,i,s,o,a,c){var u={n:e,e:t,d:r,p:i,q:s,dP:o,dQ:a,qInv:c};return u.decrypt=function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=l.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:b};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={decode:function(e){return e}};else throw Error('Unsupported encryption scheme: "'+t+'".');return t.decode(i,u,!1)},u.sign=function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):("NONE"===t||"NULL"===t||null===t)&&(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return l.rsa.encrypt(n,u,r)},u},l.wrapRsaPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(l.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,o.toDer(e).getBytes())])},l.privateKeyFromAsn1=function(e){var t,r,s,a,c,d,p,f,g={},m=[];if(o.validate(e,u,g,m)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},m=[],!o.validate(e,h,g,m)){var y=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw y.errors=m,y}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),s=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),c=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),p=n.util.createBuffer(g.privateKeyExponent2).toHex(),f=n.util.createBuffer(g.privateKeyCoefficient).toHex(),l.setRsaPrivateKey(new i(t,16),new i(r,16),new i(s,16),new i(a,16),new i(c,16),new i(d,16),new i(p,16),new i(f,16))},l.privateKeyToAsn1=l.privateKeyToRSAPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.e)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.d)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.p)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.q)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.dP)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.dQ)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.qInv))])},l.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,p,t,r)){var s=o.derToOid(t.publicKeyOid);if(s!==l.oids.rsaEncryption){var a=Error("Cannot read public key. Unknown OID.");throw a.oid=s,a}e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r)){var a=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw a.errors=r,a}var c=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return l.setRsaPublicKey(new i(c,16),new i(u,16))},l.publicKeyToAsn1=l.publicKeyToSubjectPublicKeyInfo=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(l.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[l.publicKeyToRSAPublicKey(e)])])},l.publicKeyToRSAPublicKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,v(e.e))])}},44092:function(e,t,r){var n=r(95482);r(3654),r(77939);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){o||(s=String.fromCharCode(128)+n.util.fillString("\0",64),o=!0);var e=null,t=n.util.createBuffer(),r=Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return i.start=function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,l>>>0];for(var c=i.fullMessageLength.length-1;c>=0;--c)i.fullMessageLength[c]+=l[1],l[1]=l[0]+(i.fullMessageLength[c]/4294967296>>>0),i.fullMessageLength[c]=i.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(s),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o,l=n.util.createBuffer();l.putBytes(t.bytes());var c=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;l.putBytes(s.substr(0,i.blockLength-c));for(var u=8*i.fullMessageLength[0],h=0;h>>0,l.putInt32(u>>>0),u=o>>>0;l.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,l);var p=n.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p},i};var s=null,o=!1;function a(e,t,r){for(var n,i,s,o,a,l,c,u=r.length();u>=64;){for(c=0,i=e.h0,s=e.h1,o=e.h2,a=e.h3,l=e.h4;c<16;++c)n=r.getInt32(),t[c]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+l+1518500249+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<20;++c)n=(n=t[c-3]^t[c-8]^t[c-14]^t[c-16])<<1|n>>>31,t[c]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+l+1518500249+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<32;++c)n=(n=t[c-3]^t[c-8]^t[c-14]^t[c-16])<<1|n>>>31,t[c]=n,n=(i<<5|i>>>27)+(s^o^a)+l+1859775393+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<40;++c)n=(n=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|n>>>30,t[c]=n,n=(i<<5|i>>>27)+(s^o^a)+l+1859775393+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<60;++c)n=(n=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|n>>>30,t[c]=n,n=(i<<5|i>>>27)+(s&o|a&(s^o))+l+2400959708+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<80;++c)n=(n=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|n>>>30,t[c]=n,n=(i<<5|i>>>27)+(s^o^a)+l+3395469782+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+l|0,u-=64}}},22541:function(e,t,r){var n=r(95482);r(3654),r(77939);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){o||(s=String.fromCharCode(128)+n.util.fillString("\0",64),a=[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],o=!0);var e=null,t=n.util.createBuffer(),r=Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return i.start=function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,a>>>0];for(var c=i.fullMessageLength.length-1;c>=0;--c)i.fullMessageLength[c]+=a[1],a[1]=a[0]+(i.fullMessageLength[c]/4294967296>>>0),i.fullMessageLength[c]=i.fullMessageLength[c]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),l(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o,a=n.util.createBuffer();a.putBytes(t.bytes());var c=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;a.putBytes(s.substr(0,i.blockLength-c));for(var u=8*i.fullMessageLength[0],h=0;h>>0,a.putInt32(u>>>0),u=o>>>0;a.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};l(d,r,a);var p=n.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p.putInt32(d.h5),p.putInt32(d.h6),p.putInt32(d.h7),p},i};var s=null,o=!1,a=null;function l(e,t,r){for(var n,i,s,o,l,c,u,h,d,p,f,g,m,y,b,v=r.length();v>=64;){for(u=0;u<16;++u)t[u]=r.getInt32();for(;u<64;++u)n=((n=t[u-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[u-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[u]=n+t[u-7]+i+t[u-16]|0;for(u=0,h=e.h0,d=e.h1,p=e.h2,f=e.h3,g=e.h4,m=e.h5,y=e.h6,b=e.h7;u<64;++u)o=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7),l=y^g&(m^y),s=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),c=h&d|p&(h^d),n=b+o+l+a[u]+t[u],i=s+c,b=y,y=m,m=g,g=f+n>>>0,f=p,p=d,d=h,h=n+i>>>0;e.h0=e.h0+h|0,e.h1=e.h1+d|0,e.h2=e.h2+p|0,e.h3=e.h3+f|0,e.h4=e.h4+g|0,e.h5=e.h5+m|0,e.h6=e.h6+y|0,e.h7=e.h7+b|0,v-=64}}},56334:function(e,t,r){var n=r(95482);r(3654),r(77939);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var s=n.sha384=n.sha512.sha384=n.sha512.sha384||{};s.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=s,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(o=String.fromCharCode(128)+n.util.fillString("\0",128),l=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(c={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],c["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],c["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],c["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),void 0===e&&(e="SHA-512"),!(e in c))throw Error("Invalid SHA-512 algorithm: "+e);for(var t=c[e],r=null,i=n.util.createBuffer(),s=Array(80),h=0;h<80;++h)s[h]=[,,];var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var p={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16};return p.start=function(){p.messageLength=0,p.fullMessageLength=p.messageLength128=[];for(var e=p.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=p.fullMessageLength.length-1;a>=0;--a)p.fullMessageLength[a]+=o[1],o[1]=o[0]+(p.fullMessageLength[a]/4294967296>>>0),p.fullMessageLength[a]=p.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return i.putBytes(e),u(r,s,i),(i.read>2048||0===i.length())&&i.compact(),p},p.digest=function(){var t,a,l=n.util.createBuffer();l.putBytes(i.bytes());var c=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize&p.blockLength-1;l.putBytes(o.substr(0,p.blockLength-c));for(var h=8*p.fullMessageLength[0],d=0;d>>0,l.putInt32(h>>>0),h=t>>>0;l.putInt32(h);for(var f=Array(r.length),d=0;d=128;){for(B=0;B<16;++B)t[B][0]=r.getInt32()>>>0,t[B][1]=r.getInt32()>>>0;for(;B<80;++B)n=(((N=(x=t[B-2])[0])>>>19|(L=x[1])<<13)^(L>>>29|N<<3)^N>>>6)>>>0,i=((N<<13|L>>>19)^(L<<3|N>>>29)^(N<<26|L>>>6))>>>0,s=(((N=(M=t[B-15])[0])>>>1|(L=M[1])<<31)^(N>>>8|L<<24)^N>>>7)>>>0,o=((N<<31|L>>>1)^(N<<24|L>>>8)^(N<<25|L>>>7))>>>0,O=t[B-7],U=t[B-16],L=i+O[1]+o+U[1],t[B][0]=n+O[0]+s+U[0]+(L/4294967296>>>0)>>>0,t[B][1]=L>>>0;for(B=0,m=e[0][0],y=e[0][1],b=e[1][0],v=e[1][1],w=e[2][0],E=e[2][1],S=e[3][0],A=e[3][1],I=e[4][0],_=e[4][1],T=e[5][0],C=e[5][1],R=e[6][0],k=e[6][1],P=e[7][0],D=e[7][1];B<80;++B)u=((I>>>14|_<<18)^(I>>>18|_<<14)^(_>>>9|I<<23))>>>0,h=((I<<18|_>>>14)^(I<<14|_>>>18)^(_<<23|I>>>9))>>>0,d=(R^I&(T^R))>>>0,p=(k^_&(C^k))>>>0,a=((m>>>28|y<<4)^(y>>>2|m<<30)^(y>>>7|m<<25))>>>0,c=((m<<4|y>>>28)^(y<<30|m>>>2)^(y<<25|m>>>7))>>>0,f=(m&b|w&(m^b))>>>0,g=(y&v|E&(y^v))>>>0,L=D+h+p+l[B][1]+t[B][1],n=P+u+d+l[B][0]+t[B][0]+(L/4294967296>>>0)>>>0,i=L>>>0,s=a+f+((L=c+g)/4294967296>>>0)>>>0,o=L>>>0,P=R,D=k,R=T,k=C,T=I,C=_,I=S+n+((L=A+i)/4294967296>>>0)>>>0,_=L>>>0,S=w,A=E,w=b,E=v,b=m,v=y,m=n+s+((L=i+o)/4294967296>>>0)>>>0,y=L>>>0;L=e[0][1]+y,e[0][0]=e[0][0]+m+(L/4294967296>>>0)>>>0,e[0][1]=L>>>0,L=e[1][1]+v,e[1][0]=e[1][0]+b+(L/4294967296>>>0)>>>0,e[1][1]=L>>>0,L=e[2][1]+E,e[2][0]=e[2][0]+w+(L/4294967296>>>0)>>>0,e[2][1]=L>>>0,L=e[3][1]+A,e[3][0]=e[3][0]+S+(L/4294967296>>>0)>>>0,e[3][1]=L>>>0,L=e[4][1]+_,e[4][0]=e[4][0]+I+(L/4294967296>>>0)>>>0,e[4][1]=L>>>0,L=e[5][1]+C,e[5][0]=e[5][0]+T+(L/4294967296>>>0)>>>0,e[5][1]=L>>>0,L=e[6][1]+k,e[6][0]=e[6][0]+R+(L/4294967296>>>0)>>>0,e[6][1]=L>>>0,L=e[7][1]+D,e[7][0]=e[7][0]+P+(L/4294967296>>>0)>>>0,e[7][1]=L>>>0,F-=128}}},77939:function(e,t,r){var n=r(24112),i=r(62678).Buffer,s=r(95482),o=r(16994),a=e.exports=s.util=s.util||{};function l(e){if(!(8===e||16===e||24===e||32===e))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}function c(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(a.isArrayBuffer(e)||a.isArrayBufferView(e)){if(void 0!==i&&e instanceof i)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&s.setAttribute("a",i=!i))}}a.nextTick=a.setImmediate}(),a.isNodejs=void 0!==n&&n.versions&&n.versions.node,a.globalScope=a.isNodejs?r.g:"undefined"==typeof self?window:self,a.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},a.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},a.isArrayBufferView=function(e){return e&&a.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},a.ByteBuffer=c,a.ByteStringBuffer=c,a.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},a.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},a.ByteStringBuffer.prototype.isEmpty=function(){return 0>=this.length()},a.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},a.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},a.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},a.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(a.encodeUtf8(e))},a.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},a.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},a.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},a.ByteStringBuffer.prototype.putInt=function(e,t){l(t);var r="";do t-=8,r+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(r)},a.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},a.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},a.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},a.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},a.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},a.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},a.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},a.ByteStringBuffer.prototype.copy=function(){var e=a.createBuffer(this.data);return e.read=this.read,e},a.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},a.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},a.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},a.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=this.length()},a.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},a.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},a.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},a.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},a.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},a.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},a.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},a.DataBuffer.prototype.putInt=function(e,t){l(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this},a.DataBuffer.prototype.putSignedInt=function(e,t){return l(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},a.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},a.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},a.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},a.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},a.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},a.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},a.DataBuffer.prototype.copy=function(){return new a.DataBuffer(this)},a.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},a.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},a.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},a.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},a.xorBytes=function(e,t,r){for(var n="",i="",s="",o=0,a=0;r>0;--r,++o)i=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+s},a.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],d="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";a.encode64=function(e,t){for(var r,n,i,s="",o="",a=0;a>2)+u.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":s+=u.charAt((15&n)<<2|i>>6)+(isNaN(i)?"=":u.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+s},a.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,s="",o=0;o>4),64!==n&&(s+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(s+=String.fromCharCode((3&n)<<6|i)));return s},a.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},a.decodeUtf8=function(e){return decodeURIComponent(escape(e))},a.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:o.encode,decode:o.decode}},a.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},a.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s>2)+u.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":s+=u.charAt((15&n)<<2|i>>6)+(isNaN(i)?"=":u.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+s},a.binary.base64.decode=function(e,t,r){var n,i,s,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var l=0,c=r=r||0;l>4,64!==s&&(a[c++]=(15&i)<<4|s>>2,64!==o&&(a[c++]=(3&s)<<6|o));return t?c-r:a.subarray(0,c)},a.binary.base58.encode=function(e,t){return a.binary.baseN.encode(e,d,t)},a.binary.base58.decode=function(e,t){return a.binary.baseN.decode(e,d,t)},a.text={utf8:{},utf16:{}},a.text.utf8.encode=function(e,t,r){e=a.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s0&&s.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(e.substring(o)),s.join("")},a.formatNumber=function(e,t,r,n){var i=e,s=isNaN(t=Math.abs(t))?2:t,o=void 0===n?".":n,a=i<0?"-":"",l=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",c=l.length>3?l.length%3:0;return a+(c?l.substr(0,c)+o:"")+l.substr(c).replace(/(\d{3})(?=\d)/g,"$1"+o)+(s?(void 0===r?",":r)+Math.abs(i-l).toFixed(s).slice(2):"")},a.formatSize=function(e){return e=e>=1073741824?a.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?a.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?a.formatNumber(e/1024,0)+" KiB":a.formatNumber(e,0)+" bytes"},a.bytesFromIP=function(e){return -1!==e.indexOf(".")?a.bytesFromIPv4(e):-1!==e.indexOf(":")?a.bytesFromIPv6(e):null},a.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=a.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:l,end:l})}t.push(s)}if(r.length>0){var c=r[n];c.end-c.start>0&&(t.splice(c.start,c.end-c.start+1,""),0===c.start&&t.unshift(""),7===c.end&&t.push(""))}return t.join(":")},a.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in a&&!e.update)return t(null,a.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return a.cores=navigator.hardwareConcurrency,t(null,a.cores);if("undefined"==typeof Worker)return a.cores=1,t(null,a.cores);if("undefined"==typeof Blob)return a.cores=2,t(null,a.cores);var r=URL.createObjectURL(new Blob(["(",(function(){self.addEventListener("message",function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&i.sti.st&&a.st=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,r){return this.readAtomically(()=>{if(!(t>0)||void 0!==this.readGivenChar(e))return r()})}readNumber(e,t,r,n){return this.readAtomically(()=>{let i=0,s=0,o=this.peekChar();if(void 0===o)return;let a=2**(8*n)-1;for(;;){let r=this.readAtomically(()=>{let t=this.readChar();if(void 0===t)return;let r=Number.parseInt(t,e);if(!Number.isNaN(r))return r});if(void 0===r)break;if(i*=e,(i+=r)>a||(s+=1,void 0!==t&&s>t))return}return 0===s?void 0:!r&&"0"===o&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1));if(void 0===r)return;e[t]=r}return e})}readIPv6Addr(){let e=e=>{for(let t=0;tthis.readIPv4Addr());if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}let n=this.readSeparator(":",t,()=>this.readNumber(16,4,!0,2));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n||void 0===this.readGivenChar(":")||void 0===this.readGivenChar(":"))return;let i=new Uint8Array(14),[s]=e(i.subarray(0,16-(r+2)));return t.set(i.subarray(0,s),16-s),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}let i=new n;function s(e){if(!(e.length>15))return i.new(e).parseWith(()=>i.readIPv4Addr())}function o(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return i.new(e).parseWith(()=>i.readIPv6Addr())}function a(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return i.new(e).parseWith(()=>i.readIPAddr())}},36408:function(e,t,r){"use strict";let n,i;r.d(t,{Au:function(){return tD},m2:function(){return tx},Re:function(){return tN},xO:function(){return tR},r3:function(){return tL},lR:function(){return tB}});var s,o,a,l,c,u,h,d,p={};r.r(p),r.d(p,{Ed25519PrivateKey:function(){return B},Ed25519PublicKey:function(){return D},generateKeyPair:function(){return x},generateKeyPairFromSeed:function(){return O},unmarshalEd25519PrivateKey:function(){return N},unmarshalEd25519PublicKey:function(){return L}});var f={};r.r(f),r.d(f,{MAX_RSA_KEY_SIZE:function(){return tf},RsaPrivateKey:function(){return tm},RsaPublicKey:function(){return tg},fromJwk:function(){return tv},generateKeyPair:function(){return tw},unmarshalRsaPrivateKey:function(){return ty},unmarshalRsaPublicKey:function(){return tb}});var g={};r.r(g),r.d(g,{Secp256k1PrivateKey:function(){return tI},Secp256k1PublicKey:function(){return tA},generateKeyPair:function(){return tC},unmarshalSecp256k1PrivateKey:function(){return t_},unmarshalSecp256k1PublicKey:function(){return tT}});var m=r(22852),y=r(75360),b=r(60575),v=r(30024),w=r(38856),E=r(60565);function S(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}var A=r(36562);function I(e,t){let r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}var _=r(84018),T=r(83508),C={get(e=globalThis){let t=e.crypto;if(null==t||null==t.subtle)throw Object.assign(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 t}};let R={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function k(e,t){let r=function(e){let t=(void 0)??"AES-GCM",r=(void 0)??16,n=(void 0)??12,i=e?.digest??"SHA-256",s=e?.saltLength??16,o=e?.iterations??32767,a=C.get();async function l(e,l){let c;let u=a.getRandomValues(new Uint8Array(s)),h={name:t,iv:a.getRandomValues(new Uint8Array(n))};if("string"==typeof l&&(l=(0,E.m)(l)),0===l.length){c=await a.subtle.importKey("jwk",R,{name:"AES-GCM"},!0,["encrypt"]);try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}catch{c=await a.subtle.importKey("jwk",R,{name:"AES-GCM"},!0,["encrypt"])}}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}let d=await a.subtle.encrypt(h,c,e);return(0,T.z)([u,h.iv,new Uint8Array(d)])}async function c(e,l){let c;let u=e.subarray(0,s),h=e.subarray(s,s+n),d=e.subarray(s+n);if("string"==typeof l&&(l=(0,E.m)(l)),0===l.length)try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}catch{c=await a.subtle.importKey("jwk",R,{name:"AES-GCM"},!0,["decrypt"])}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}return new Uint8Array(await a.subtle.decrypt({name:t,iv:h},c,d))}return r*=8,{encrypt:l,decrypt:c}}(),n=await r.encrypt(e,t);return _.base64.encode(n)}var P=r(47971);(s=c||(c={})).RSA="RSA",s.Ed25519="Ed25519",s.Secp256k1="Secp256k1",(o=u||(u={}))[o.RSA=0]="RSA",o[o.Ed25519=1]="Ed25519",o[o.Secp256k1=2]="Secp256k1",(c||(c={})).codec=()=>(0,P.Ji)(u),(a=h||(h={})).codec=()=>(null==n&&(n=(0,P.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),c.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=c.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),n),a.encode=e=>(0,P.LE)(e,a.codec()),a.decode=e=>(0,P.C6)(e,a.codec()),(l=d||(d={})).codec=()=>(null==i&&(i=(0,P.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),c.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=c.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),i),l.encode=e=>(0,P.LE)(e,l.codec()),l.decode=e=>(0,P.C6)(e,l.codec());class D{_key;constructor(e){this._key=M(e,32)}verify(e,t){var r;return r=this._key,A.UN.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}marshal(){return this._key}get bytes(){return h.encode({Type:c.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,w.f)(this.bytes,e.bytes)}hash(){let e=v.sha256.digest(this.bytes);return S(e)?e.then(({bytes:e})=>e):e.bytes}}class B{_key;_publicKey;constructor(e,t){this._key=M(e,64),this._publicKey=M(t,32)}sign(e){return function(e,t){let r=e.subarray(0,32);return A.UN.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new D(this._publicKey)}marshal(){return this._key}get bytes(){return d.encode({Type:c.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,w.f)(this.bytes,e.bytes)}async hash(){let e;let t=v.sha256.digest(this.bytes);return S(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let e=b.identity.digest(this.public.bytes);return y.base58btc.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return k(this.bytes,e);throw new m.sv(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function N(e){return e.length>64?new B((e=M(e,96)).subarray(0,64),e.subarray(64,e.length)):new B((e=M(e,64)).subarray(0,64),e.subarray(32))}function L(e){return new D(e=M(e,32))}async function x(){let{privateKey:e,publicKey:t}=function(){let e=A.UN.utils.randomPrivateKey(),t=A.UN.getPublicKey(e);return{privateKey:I(e,t),publicKey:t}}();return new B(e,t)}async function O(e){let{privateKey:t,publicKey:r}=function(e){if(32!==e.length)throw TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=A.UN.getPublicKey(e);return{privateKey:I(e,t),publicKey:t}}(e);return new B(t,r)}function M(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new m.sv(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}var U=r(12528);async function F(e){let t=await C.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await $(t);return{privateKey:r[0],publicKey:r[1]}}async function K(e){let t=[await C.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await q(e)],r=await $({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function V(e,t){let r=await C.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await C.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function H(e,t,r){let n=await C.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return C.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function $(e){if(null==e.privateKey||null==e.publicKey)throw new m.sv("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([C.get().subtle.exportKey("jwk",e.privateKey),C.get().subtle.exportKey("jwk",e.publicKey)])}async function q(e){return C.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function z(e){if("RSA"!==e.kty)throw new m.sv("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new m.sv("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*(0,E.m)(e.n,"base64url").length}var j=r(65376),G=r(93557),W=r(68104);async function Y(e,t,r,n){var i;let s;let{c:o,dkLen:a,asyncTick:l,DK:c,PRF:u,PRFSalt:h}=function(e,t,r,n){(0,j.vp)(e);let{c:i,dkLen:s,asyncTick:o}=(0,W.U5)({dkLen:32,asyncTick:10},n);if((0,j.Rx)(i),(0,j.Rx)(s),(0,j.Rx)(o),i<1)throw Error("PBKDF2: iterations (c) should be >= 1");let a=(0,W.O0)(t),l=(0,W.O0)(r),c=new Uint8Array(s),u=G.b.create(e,a),h=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:o,DK:c,PRF:u,PRFSalt:h}}(e,t,r,n),d=new Uint8Array(4),p=(0,W.GL)(d),f=new Uint8Array(u.outputLen);for(let e=1,t=0;t{u._cloneInto(s).update(f).digestInto(f);for(let e=0;e=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function Z(e,t,r=-1){let n=e,i=0,s=Math.pow(2,t);for(let o=1;o<8;o++){if(e=0;e--){let r=Math.pow(2,e*t);s[i-e-1]=Math.floor(n/r),n-=s[i-e-1]*r}return e}s*=Math.pow(2,t)}return new ArrayBuffer(0)}function ee(...e){let t=0,r=0;for(let r of e)t+=r.length;let n=new Uint8Array(new ArrayBuffer(t));for(let t of e)n.set(t,r),r+=t.length;return n}function et(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let t=255===e[0]&&128&e[1],r=0===e[0]&&(128&e[1])==0;(t||r)&&this.warnings.push("Needlessly long format")}let t=new Uint8Array(new ArrayBuffer(this.valueHex.byteLength));for(let e=0;e=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){let e=new Uint8Array(r+=255);for(let r=0;r8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let o=t+1,a=n.subarray(o,o+s);return 0===a[s-1]&&this.warnings.push("Needlessly long encoded length"),this.length=X(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&((r=new Uint8Array(t))[0]=128),t;if(this.longFormUsed){let n=Z(this.length,8);if(n.byteLength>127)return this.error="Too big length",ec;if(t=new ArrayBuffer(n.byteLength+1),e)return t;let i=new Uint8Array(n);(r=new Uint8Array(t))[0]=128|n.byteLength;for(let e=0;e=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};a=ev.EndOfContent;break;case 1:a=ev.Boolean;break;case 2:a=ev.Integer;break;case 3:a=ev.BitString;break;case 4:a=ev.OctetString;break;case 5:a=ev.Null;break;case 6:a=ev.ObjectIdentifier;break;case 10:a=ev.Enumerated;break;case 12:a=ev.Utf8String;break;case 13:a=ev.RelativeObjectIdentifier;break;case 14:a=ev.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=ev.Sequence;break;case 17:a=ev.Set;break;case 18:a=ev.NumericString;break;case 19:a=ev.PrintableString;break;case 20:a=ev.TeletexString;break;case 21:a=ev.VideotexString;break;case 22:a=ev.IA5String;break;case 23:a=ev.UTCTime;break;case 24:a=ev.GeneralizedTime;break;case 25:a=ev.GraphicString;break;case 26:a=ev.VisibleString;break;case 27:a=ev.GeneralString;break;case 28:a=ev.UniversalString;break;case 29:a=ev.CharacterString;break;case 30:a=ev.BmpString;break;case 31:a=ev.DATE;break;case 32:a=ev.TimeOfDay;break;case 33:a=ev.DateTime;break;case 34:a=ev.Duration;break;default:{let e=i.idBlock.isConstructed?new ev.Constructed:new ev.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?ev.Constructed:ev.Primitive;return o=(i=function(e,t){if(e instanceof t)return e;let r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,a)).fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(n,n+i.blockLength),{offset:o,result:i}}function e_(e){if(!e.byteLength){let e=new ew({},em);return e.error="Input buffer has zero length",{offset:-1,result:e}}return eI(J.vJ.toUint8Array(e).slice(),0,e.byteLength)}ev.Primitive=eA,eA.NAME="PRIMITIVE";class eT extends em{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){var n,i;let s=J.vJ.toUint8Array(e);if(!es(this,s,t,r))return -1;if(this.valueBeforeDecodeView=s.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let o=t;for(;n=this.isIndefiniteForm,i=r,(n?1:i)>0;){let e=eI(s,o,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(o=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===eh)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===eh?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){let r=t||new eo;for(let t=0;t` ${e}`).join("\n"));let t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} : +${e.join("\n")}`:`${t} :`}}ev.Constructed=eC,eC.NAME="CONSTRUCTED";class eR extends em{fromBER(e,t,r){return t}toBER(e){return ec}}eR.override="EndOfContentValueBlock";class ek extends ew{constructor(e={}){super(e,eR),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}ev.EndOfContent=ek,ek.NAME=eh;class eP extends ew{constructor(e={}){super(e,em),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){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+=r,t+r>e.byteLength)?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){let r=new ArrayBuffer(2);if(!e){let e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}ev.Null=eP,eP.NAME="NULL";class eD extends ef(em){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=J.vJ.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,r){let n=J.vJ.toUint8Array(e);return es(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,et.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}eD.NAME="BooleanValueBlock";class eB extends ew{constructor(e={}){super(e,eD),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}`}}ev.Boolean=eB,eB.NAME="BOOLEAN";class eN extends ef(eT){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=eT.prototype.fromBER.call(this,e,t,r)))return n;for(let e=0;e0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return n}let i=J.vJ.toUint8Array(e);if(!es(this,i,t,r))return -1;let s=i.subarray(t,t+r);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let e=s.subarray(1);try{if(e.byteLength){let t=eI(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+r}toBER(e,t){if(this.isConstructed)return eT.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ec;let r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}ex.NAME="BitStringValueBlock";class eO extends ew{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,i;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},ex),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return eC.prototype.onAsciiEncoding.call(this);{let e=[];for(let t of this.valueBlock.valueHexView)e.push(t.toString(2).padStart(8,"0"));let t=e.join("");return`${this.constructor.NAME} : ${t.substring(0,t.length-this.valueBlock.unusedBits)}`}}}function eM(e){if(e>=ea.length)for(let t=ea.length;t<=e;t++){let e=new Uint8Array([0]),r=ea[t-1].slice(0);for(let t=r.length-1;t>=0;t--){let n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=ee(e,r)),ea.push(r)}return ea[e]}ev.BitString=eO,eO.NAME=ep;class eU extends ef(em){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(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=et.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){let t=e<0?-1*e:e,r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){let e=Z(r-t,8,n),i=new Uint8Array(e);return i[0]|=128,e}let i=Z(t,8,n),s=new Uint8Array(i);if(128&s[0]){let e=i.slice(0),t=new Uint8Array(e);s=new Uint8Array(i=new ArrayBuffer(i.byteLength+1));for(let r=0;r1&&(n=s.length+1),this.valueHexView=s.subarray(n-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(128&t[0])!=0:{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&(128&t[1])==0:this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){let n=super.fromBER(e,t,r);return -1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e;let t=8*this.valueHexView.length-1,r=new Uint8Array(8*this.valueHexView.length/3),n=0,i=this.valueHexView,s="",o=!1;for(let o=i.byteLength-1;o>=0;o--){e=i[o];for(let i=0;i<8;i++)(1&e)==1&&(n===t?(r=function(e,t){let r,n=0,i=new Uint8Array(e),s=new Uint8Array(t),o=i.slice(0),a=o.length-1,l=s.slice(0),c=l.length-1,u=0;for(let e=c;e>=0;e--,u++)!0==(r=o[a-u]-l[c-u]-n)<0?(n=1,o[a-u]=r+10):(n=0,o[a-u]=r);if(n>0)for(let e=a-c+1;e>=0;e--,u++)if((r=o[a-u]-n)<0)n=1,o[a-u]=r+10;else{n=0,o[a-u]=r;break}return o.slice()}(eM(n),r),s="-"):r=function(e,t){let r=new Uint8Array([0]),n=new Uint8Array(e),i=new Uint8Array(t),s=n.slice(0),o=s.length-1,a=i.slice(0),l=a.length-1,c=0,u=l=0;e--,h++)c=!0==h=s.length)?s=ee(new Uint8Array([c%10]),s):s[o-h]=c%10;return r[0]>0&&(s=ee(r,s)),s}(r,eM(n))),n++,e>>=1}for(let e=0;e0;){let t=new eV;if(-1===(n=t.fromBER(e,n,r))){this.blockLength=0,this.error=t.error;break}0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){let t=[];for(let r=0;rNumber.MAX_SAFE_INTEGER){en();let t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r0;){let t=new eq;if(-1===(n=t.fromBER(e,n,r))){this.blockLength=0,this.error=t.error;break}this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){let r=[];for(let t=0;t4)continue;let i=4-t.length;for(let e=t.length-1;e>=0;e--)r[4*n+e+i]=t[e]}this.valueBlock.value=e}}e2.NAME="UniversalStringValueBlock";class e3 extends e2{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}ev.UniversalString=e3,e3.NAME="UniversalString";class e4 extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}ev.NumericString=e4,e4.NAME="NumericString";class e6 extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}ev.PrintableString=e6,e6.NAME="PrintableString";class e5 extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}ev.TeletexString=e5,e5.NAME="TeletexString";class e8 extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}ev.VideotexString=e8,e8.NAME="VideotexString";class e9 extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}ev.IA5String=e9,e9.NAME="IA5String";class e7 extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}ev.GraphicString=e7,e7.NAME="GraphicString";class te extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}ev.VisibleString=te,te.NAME="VisibleString";class tt extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}ev.GeneralString=tt,tt.NAME="GeneralString";class tr extends eJ{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}ev.CharacterString=tr,tr.NAME="CharacterString";class tn extends te{constructor({value:e,valueDate:t,...r}={}){if(super(r),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 t=0;t=50?this.year=1900+r:this.year=2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){let e=Array(7);return e[0]=er(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=er(this.month,2),e[2]=er(this.day,2),e[3]=er(this.hour,2),e[4]=er(this.minute,2),e[5]=er(this.second,2),e[6]="Z",e.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}}}ev.UTCTime=tn,tn.NAME="UTCTime";class ti extends tn{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(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,r=!1,n="",i="",s=0,o=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{if(isNaN(new Number(e[e.length-1]).valueOf()))throw Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+")||-1!==n.indexOf("-"))throw Error("Wrong input string for conversion")}else{let e=1,t=n.indexOf("+"),r="";if(-1===t&&(t=n.indexOf("-"),e=-1),-1!==t){if(r=n.substring(t+1),n=n.substring(0,t),2!==r.length&&4!==r.length)throw Error("Wrong input string for conversion");let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw Error("Wrong input string for conversion");if(o=e*i,4===r.length){if(isNaN((i=parseInt(r.substring(2,4),10)).valueOf()))throw Error("Wrong input string for conversion");a=e*i}}}let l=n.indexOf(".");if(-1===l&&(l=n.indexOf(",")),-1!==l){let e=new Number(`0${n.substring(l)}`);if(isNaN(e.valueOf()))throw Error("Wrong input string for conversion");s=e.valueOf(),i=n.substring(0,l)}else i=n;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/ig,-1!==l)throw Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,-1!==l){let e=60*s;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,-1!==l){let e=60*s;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,-1!==l){let e=1e3*s;this.millisecond=Math.floor(e)}break;default:throw Error("Wrong input string for conversion")}let c=t.exec(i);if(null===c)throw Error("Wrong input string for conversion");for(let e=1;e0&&(t=`0${t}`);let r=t.length/2,n=new Uint8Array(r),i=0,s=0;for(;i0&&(r=`0${r}`),t.push(r)}),BigInt("0x"+t.join(""))}async function tp(e,t){let r=C.get(),n=new eG({value:[new eF({value:0}),new eG({value:[new e$({value:"1.2.840.113549.1.1.1"}),new eP]}),new eL({valueHex:e.marshal()})]}).toBER(),i=new Uint8Array(n,0,n.byteLength),s=(0,tu.Z)(16),o=await Y(Q.o,t,s,{c:1e4,dkLen:32}),a=(0,tu.Z)(16),l=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),c=await r.subtle.encrypt({name:"AES-CBC",iv:a},l,i),u=new eG({value:[new eL({valueHex:s}),new eF({value:1e4}),new eF({value:32}),new eG({value:[new e$({value:"1.2.840.113549.2.11"}),new eP]})]}),h=new eG({value:[new e$({value:"1.2.840.113549.1.5.13"}),new eG({value:[new eG({value:[new e$({value:"1.2.840.113549.1.5.12"}),u]}),new eG({value:[new e$({value:"2.16.840.1.101.3.4.1.42"}),new eL({valueHex:a})]})]})]}),d=new eG({value:[h,new eL({valueHex:c})]}).toBER(),p=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...(0,U.B)(p,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}let tf=8192;class tg{_key;constructor(e){this._key=e}verify(e,t){return H(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new m.sv("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new eG({value:[new eG({value:[new e$({value:"1.2.840.113549.1.1.1"}),new eP]}),new eO({valueHex:new eG({value:[eF.fromBigInt(td((0,E.m)(e.n,"base64url"))),eF.fromBigInt(td((0,E.m)(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return h.encode({Type:c.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,w.f)(this.bytes,e.bytes)}hash(){let e=v.sha256.digest(this.bytes);return S(e)?e.then(({bytes:e})=>e):e.bytes}}class tm{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return tu.Z(16)}sign(e){return V(this._key,e)}get public(){if(null==this._publicKey)throw new m.sv("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new tg(this._publicKey)}marshal(){return function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new m.sv("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new eG({value:[new eF({value:0}),eF.fromBigInt(td((0,E.m)(e.n,"base64url"))),eF.fromBigInt(td((0,E.m)(e.e,"base64url"))),eF.fromBigInt(td((0,E.m)(e.d,"base64url"))),eF.fromBigInt(td((0,E.m)(e.p,"base64url"))),eF.fromBigInt(td((0,E.m)(e.q,"base64url"))),eF.fromBigInt(td((0,E.m)(e.dp,"base64url"))),eF.fromBigInt(td((0,E.m)(e.dq,"base64url"))),eF.fromBigInt(td((0,E.m)(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return d.encode({Type:c.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,w.f)(this.bytes,e.bytes)}hash(){let e=v.sha256.digest(this.bytes);return S(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,U.B)(e,"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return tp(this,e);if("libp2p-key"===t)return k(this.bytes,e);throw new m.sv(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function ty(e){let t=function(e){let{result:t}=e_(e),r=t.valueBlock.value;return{n:(0,U.B)(th(r[1].toBigInt()),"base64url"),e:(0,U.B)(th(r[2].toBigInt()),"base64url"),d:(0,U.B)(th(r[3].toBigInt()),"base64url"),p:(0,U.B)(th(r[4].toBigInt()),"base64url"),q:(0,U.B)(th(r[5].toBigInt()),"base64url"),dp:(0,U.B)(th(r[6].toBigInt()),"base64url"),dq:(0,U.B)(th(r[7].toBigInt()),"base64url"),qi:(0,U.B)(th(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(z(t)>tf)throw new m.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await K(t);return new tm(r.privateKey,r.publicKey)}function tb(e){let t=function(e){let{result:t}=e_(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:(0,U.B)(th(r[0].toBigInt()),"base64url"),e:(0,U.B)(th(r[1].toBigInt()),"base64url")}}(e);if(z(t)>tf)throw new m.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new tg(t)}async function tv(e){if(z(e)>tf)throw new m.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await K(e);return new tm(t.privateKey,t.publicKey)}async function tw(e){if(e>tf)throw new m.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await F(e);return new tm(t.privateKey,t.publicKey)}var tE=r(14374);function tS(e){try{tE.kA.ProjectivePoint.fromHex(e)}catch(e){throw new m.sv(String(e),"ERR_INVALID_PUBLIC_KEY")}}class tA{_key;constructor(e){tS(e),this._key=e}verify(e,t){return function(e,t,r){let n=v.sha256.digest(r instanceof Uint8Array?r:r.subarray());if(S(n))return n.then(({digest:r})=>tE.kA.verify(t,r,e)).catch(e=>{throw new m.sv(String(e),"ERR_INVALID_INPUT")});try{return tE.kA.verify(t,n.digest,e)}catch(e){throw new m.sv(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){var e;return e=this._key,tE.kA.ProjectivePoint.fromHex(e).toRawBytes(!0)}get bytes(){return h.encode({Type:c.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,w.f)(this.bytes,e.bytes)}async hash(){let e;let t=v.sha256.digest(this.bytes);return S(t)?{bytes:e}=await t:e=t.bytes,e}}class tI{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return tE.kA.getPublicKey(e,!0)}catch(e){throw new m.sv(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{tE.kA.getPublicKey(e,!0)}catch(e){throw new m.sv(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),tS(this._publicKey)}sign(e){return function(e,t){let r=v.sha256.digest(t instanceof Uint8Array?t:t.subarray());if(S(r))return r.then(({digest:t})=>tE.kA.sign(t,e).toDERRawBytes()).catch(e=>{throw new m.sv(String(e),"ERR_INVALID_INPUT")});try{return tE.kA.sign(r.digest,e).toDERRawBytes()}catch(e){throw new m.sv(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new tA(this._publicKey)}marshal(){return this._key}get bytes(){return d.encode({Type:c.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,w.f)(this.bytes,e.bytes)}hash(){let e=v.sha256.digest(this.bytes);return S(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,U.B)(e,"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return k(this.bytes,e);throw new m.sv(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function t_(e){return new tI(e)}function tT(e){return new tA(e)}async function tC(){return new tI(tE.kA.utils.randomPrivateKey())}let tR={rsa:f,ed25519:p,secp256k1:g};function tk(e){let t=Object.keys(tR).join(" / ");return new m.sv(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function tP(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return tR[e];throw tk(e)}async function tD(e,t){return tP(e).generateKeyPair(t??2048)}function tB(e){let t=h.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case c.RSA:return tR.rsa.unmarshalRsaPublicKey(r);case c.Ed25519:return tR.ed25519.unmarshalEd25519PublicKey(r);case c.Secp256k1:return tR.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw tk(t.Type??"unknown")}}function tN(e,t){return tP(t=(t??"rsa").toLowerCase()),e.bytes}async function tL(e){let t=d.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case c.RSA:return tR.rsa.unmarshalRsaPrivateKey(r);case c.Ed25519:return tR.ed25519.unmarshalEd25519PrivateKey(r);case c.Secp256k1:return tR.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw tk(t.Type??"RSA")}}function tx(e,t){return tP(t=(t??"rsa").toLowerCase()),e.bytes}},34018:function(e,t,r){"use strict";r.d(t,{Z:function(){return s}});var n=r(22852),i=r(68104);function s(e){if(isNaN(e)||e<=0)throw new n.sv("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return(0,i.O6)(e)}},22852:function(e,t,r){"use strict";r.d(t,{J5:function(){return s},Vc:function(){return a},_L:function(){return n},l9:function(){return o},sv:function(){return i}});class n extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=n.code,this.type=n.type}static code="ABORT_ERR";static type="aborted"}class i extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class s extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}let o="ERR_TIMEOUT",a="ERR_NOT_FOUND"},85931:function(e,t,r){"use strict";r.d(t,{A:function(){return o},L:function(){return i}});var n=r(5036);class i extends EventTarget{#e=new Map;constructor(){super(),(0,n.W)(1/0,this)}listenerCount(e){let t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter(({callback:e})=>e!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),r=this.#e.get(e.type);return null==r||(r=r.filter(({once:e})=>!e),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new o(e,t))}}class s extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}}let o=globalThis.CustomEvent??s},5036:function(e,t,r){"use strict";r.d(t,{W:function(){return n}});let n=(e,...t)=>{}},5846:function(e,t,r){"use strict";r.d(t,{J:function(){return n}});let n=Symbol.for("@libp2p/peer-discovery")},25906:function(e,t,r){"use strict";r.d(t,{C:function(){return n},I:function(){return i}});let n=Symbol.for("@libp2p/peer-id");function i(e){return null!=e&&!!e[n]}},90678:function(e,t,r){"use strict";r.d(t,{n9:function(){return o},pG:function(){return c}});var n=r(36408),i=r(65301),s=r(60565);let o=async()=>{let e=await (0,n.Au)("Ed25519"),t=await l(e);if("Ed25519"===t.type)return t;throw Error(`Generated unexpected PeerId type "${t.type}"`)};async function a(e){return(0,i.y5)((0,n.Re)(e))}async function l(e){return(0,i.y5)((0,n.Re)(e.public),(0,n.m2)(e))}async function c(e){return u((0,s.m)(e.id,"base58btc"),null!=e.privKey?(0,s.m)(e.privKey,"base64pad"):void 0,null!=e.pubKey?(0,s.m)(e.pubKey,"base64pad"):void 0)}async function u(e,t,r){return null!=t?l(await (0,n.r3)(t)):null!=r?a((0,n.lR)(r)):(0,i.cv)(e)}},65301:function(e,t,r){"use strict";r.d(t,{cv:function(){return w},jE:function(){return v},vL:function(){return b},y5:function(){return E}});var n=r(22852),i=r(25906),s=r(75360),o=r(74006),a=r(45193),l=r(2780),c=r(60575),u=r(30024),h=r(38856);let d=Symbol.for("nodejs.util.inspect.custom"),p=Object.values(o.gh).map(e=>e.decoder).reduce((e,t)=>e.or(t),o.gh.identity.decoder);class f{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()})`}[i.C]=!0;toString(){return null==this.string&&(this.string=s.base58btc.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return a.k0.createV1(114,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return(0,h.f)(this.multihash.bytes,e);if("string"==typeof e)return v(e).equals(this);if(e?.multihash?.bytes!=null)return(0,h.f)(this.multihash.bytes,e.multihash.bytes);throw Error("not valid Id")}[d](){return`PeerId(${this.toString()})`}}class g extends f{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class m extends f{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class y extends f{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}function b(e){if("RSA"===e.type)return new g(e);if("Ed25519"===e.type)return new m(e);if("secp256k1"===e.type)return new y(e);throw new n.sv("Not a PeerId","ERR_INVALID_PARAMETERS")}function v(e,t){if(t=t??p,"1"===e.charAt(0)||"Q"===e.charAt(0)){let t=l.Jx(s.base58btc.decode(`z${e}`));return e.startsWith("12D")?new m({multihash:t}):e.startsWith("16U")?new y({multihash:t}):new g({multihash:t})}return w(p.decode(e))}function w(e){try{let t=l.Jx(e);if(t.code===c.identity.code){if(36===t.digest.length)return new m({multihash:t});if(37===t.digest.length)return new y({multihash:t})}if(t.code===u.sha256.code)return new g({multihash:t})}catch{return function(e){if(null==e||null==e.multihash||null==e.version||1===e.version&&114!==e.code)throw Error("Supplied PeerID CID is invalid");let t=e.multihash;if(t.code===u.sha256.code)return new g({multihash:e.multihash});if(t.code===c.identity.code){if(36===t.digest.length)return new m({multihash:e.multihash});if(37===t.digest.length)return new y({multihash:e.multihash})}throw Error("Supplied PeerID CID is invalid")}(a.k0.decode(e))}throw Error("Supplied PeerID CID is invalid")}async function E(e,t){return 36===e.length?new m({multihash:l.Ue(c.identity.code,e),privateKey:t}):37===e.length?new y({multihash:l.Ue(c.identity.code,e),privateKey:t}):new g({multihash:await u.sha256.digest(e),publicKey:e,privateKey:t})}},88695:function(e,t,r){"use strict";let n;r.d(t,{Fm:function(){return w},xV:function(){return v}}),r(12143),parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var i=r(60522),s=r(75360),o=r(74006),a=r(45193),l=r(2780),c=r(17954),u=r(83508),h=r(60565),d=r(12528),p=r(74369);let f=p.C,g=p.aY,m=function(e){let t=0;if(f(e=e.toString().trim())){let r=new Uint8Array(t+4);return e.split(/\./g).forEach(e=>{r[t++]=255&parseInt(e,10)}),r}if(g(e)){let r;let n=e.split(":",8);for(r=0;r0;r--)e.push("0");n.splice.apply(n,e)}let i=new Uint8Array(t+16);for(r=0;r>8&255,i[t++]=255&e}return i}throw Error("invalid ip address")},y=function(e,t=0,r){t=~~t,r=r??e.length-t;let n=new DataView(e.buffer);if(4===r){let n=[];for(let i=0;i65536)throw Error("Port number is not in range(1, 65536)");let s=A(n);return(0,u.z)([r,s],r.length+s.length)}(t);case 445:return function(e){let t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=i.base32.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");let s=A(n);return(0,u.z)([r,s],r.length+s.length)}(t);case 466:return function(e){let t=S.decode(e),r=Uint8Array.from(c.cv(t.length));return(0,u.z)([r,t],r.length+t.length)}(t);default:return(0,h.m)(t,"base16")}}(0,b.Ev)("ip4"),(0,b.Ev)("ip6"),(0,b.Ev)("ipcidr");let E=Object.values(o.gh).map(e=>e.decoder),S=(n=E[0].or(E[1]),E.slice(2).forEach(e=>n=n.or(e)),n);function A(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function I(e){return new DataView(e.buffer).getUint16(e.byteOffset)}},40914:function(e,t,r){"use strict";r.d(t,{h2:function(){return S},HM:function(){return A},a_:function(){return h.Ev},s_:function(){return E}});var n=r(22852),i=r(75360),s=r(45193),o=r(38856),a=r(12528),l=r(17954),c=r(83508),u=r(88695),h=r(27304);function d(e){let t=[],r=[],n=null,i=0;for(;i0)return e.size/8;if(0===e.size)return 0;{let e=l.Jx(t instanceof Uint8Array?t:Uint8Array.from(t));return e+l.P$(e)}}(c,e.slice(i+o));if(0===d){t.push([s]),r.push([s]),i+=o;continue}let p=e.slice(i+o,i+o+d);if((i+=d+o)>e.length)throw m("Invalid address Uint8Array: "+(0,a.B)(e,"base16"));t.push([s,p]);let f=(0,u.xV)(s,p);if(r.push([s,f]),!0===c.path){n=f;break}}return{bytes:Uint8Array.from(e),string:p(r),tuples:t,stringTuples:r,path:n}}function p(e){let t=[];return e.map(e=>{let r=(0,h.Ev)(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null}),g(t.join("/"))}function f(e){return(0,c.z)(e.map(e=>{let t=(0,h.Ev)(e[0]),r=Uint8Array.from(l.cv(t.code));return e.length>1&&null!=e[1]&&(r=(0,c.z)([r,e[1]])),r}))}function g(e){return"/"+e.trim().split("/").filter(e=>e).join("/")}function m(e){return Error("Error parsing address: "+e)}let y=Symbol.for("nodejs.util.inspect.custom"),b=Symbol.for("@multiformats/js-multiaddr/multiaddr"),v=[(0,h.Ev)("dns").code,(0,h.Ev)("dns4").code,(0,h.Ev)("dns6").code,(0,h.Ev)("dnsaddr").code];class w{bytes;#t;#r;#n;#i;[b]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=d(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw Error(`multiaddr "${e}" must start with a "/"`);t=function(e){e=g(e);let t=[],r=[],n=null,i=e.split("/").slice(1);if(1===i.length&&""===i[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s=i.length)throw m("invalid address: "+e);if(!0===a.path){n=g(i.slice(s).join("/")),t.push([a.code,(0,u.Fm)(a.code,n)]),r.push([a.code,n]);break}let l=(0,u.Fm)(a.code,i[s]);t.push([a.code,l]),r.push([a.code,(0,u.xV)(a.code,l)])}return{string:p(r),bytes:f(t),tuples:t,stringTuples:r,path:n}}(e)}else if(S(e))t=d(e.bytes);else throw Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#i=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n;let i="",s=(0,h.Ev)("tcp"),o=(0,h.Ev)("udp"),a=(0,h.Ev)("ip4"),l=(0,h.Ev)("ip6"),c=(0,h.Ev)("dns6"),u=(0,h.Ev)("ip6zone");for(let[d,p]of this.stringTuples())d===u.code&&(i=`%${p??""}`),v.includes(d)&&(t=s.name,n=443,r=`${p??""}${i}`,e=d===c.code?6:4),(d===s.code||d===o.code)&&(t=(0,h.Ev)(d).name,n=parseInt(p??"")),(d===a.code||d===l.code)&&(t=(0,h.Ev)(d).name,r=`${p??""}${i}`,e=d===l.code?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}protos(){return this.#r.map(([e])=>Object.assign({},(0,h.Ev)(e)))}protoCodes(){return this.#r.map(([e])=>e)}protoNames(){return this.#r.map(([e])=>(0,h.Ev)(e).name)}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new w(e),new w(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new w(r.slice(0,n))}decapsulateCode(e){let t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new w(f(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([t,r])=>{t===h.R5.p2p.code&&e.push([t,r]),t===h.R5["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let e=t[1];if("Q"===e[0]||"1"===e[0])return(0,a.B)(i.base58btc.decode(`z${e}`),"base58btc");return(0,a.B)(s.k0.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#i}equals(e){return(0,o.f)(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(e=>e.resolvable);if(null==t)return[this];let r=E.get(t.name);if(null==r)throw new n.sv(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await r(this,e)).map(e=>A(e))}nodeAddress(){let e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw 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 2===t.length&&(4===t[0].code||41===t[0].code)&&(6===t[1].code||273===t[1].code)}[y](){return`Multiaddr(${this.#t})`}}let E=new Map;function S(e){return!!e?.[b]}function A(e){return new w(e)}},27304:function(e,t,r){"use strict";r.d(t,{Ev:function(){return s},R5:function(){return n}});let n={},i={};function s(e){if("number"==typeof e){if(null!=i[e])return i[e];throw Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=n[e])return n[e];throw Error(`no protocol with name: ${e}`)}throw Error(`invalid protocol id type: ${typeof e}`)}[[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"]].forEach(e=>{let t=function(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:!!n,path:!!i}}(...e);i[t.code]=t,n[t.name]=t})},36562:function(e,t,r){"use strict";r.d(t,{UN:function(){return P},Sg:function(){return D}});var n=r(78967),i=r(68104),s=r(53554),o=r(91678),a=r(65332);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let l=BigInt(0),c=BigInt(1),u=BigInt(2),h=BigInt(8),d={zip215:!0},p=BigInt(0),f=BigInt(1),g=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),m=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),y=BigInt(0),b=BigInt(1),v=BigInt(2),w=BigInt(5),E=BigInt(10),S=BigInt(20),A=BigInt(40),I=BigInt(80);function _(e){let t=e*e%g*e%g,r=(0,s.oA)(t,v,g)*t%g,n=(0,s.oA)(r,b,g)*e%g,i=(0,s.oA)(n,w,g)*n%g,o=(0,s.oA)(i,E,g)*i%g,a=(0,s.oA)(o,S,g)*o%g,l=(0,s.oA)(a,A,g)*a%g,c=(0,s.oA)(l,I,g)*l%g,u=(0,s.oA)(c,I,g)*l%g,h=(0,s.oA)(u,E,g)*i%g;return{pow_p_5_8:(0,s.oA)(h,v,g)*e%g,b2:t}}function T(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function C(e,t){let r=(0,s.wQ)(t*t*t,g),n=_(e*(0,s.wQ)(r*r*t,g)).pow_p_5_8,i=(0,s.wQ)(e*r*n,g),o=(0,s.wQ)(t*i*i,g),a=i,l=(0,s.wQ)(i*m,g),c=o===e,u=o===(0,s.wQ)(-e,g),h=o===(0,s.wQ)(-e*m,g);return c&&(i=a),(u||h)&&(i=l),(0,s.Tu)(i,g)&&(i=(0,s.wQ)(-i,g)),{isValid:c||u,value:i}}let R=(0,s.gN)(g,void 0,!0),k={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:R,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:n.o,randomBytes:i.O6,adjustScalarBytes:T,uvRatio:C},P=function(e){let t=function(e){let t=(0,a.K)(e);return o.FF(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n:n,prehash:i,hash:p,randomBytes:f,nByteLength:g,h:m}=t,y=u<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:l}}}),w=t.adjustScalarBytes||(e=>e),E=t.domain||((e,t,r)=>{if(t.length||r)throw Error("Contexts/pre-hash are not supported");return e}),S=e=>"bigint"==typeof e&&lS(e)&&S(t)&&ee===l||A(e,y);function _(e,t){if(A(e,t))return e;throw Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function T(e){return e===l?e:_(e,n)}let C=new Map;function R(e){if(!(e instanceof k))throw Error("ExtendedPoint expected")}class k{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!I(e))throw Error("x required");if(!I(t))throw Error("y required");if(!I(r))throw Error("z required");if(!I(n))throw Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof k)throw Error("extended point not allowed");let{x:t,y:r}=e||{};if(!I(t)||!I(r))throw Error("invalid affine point");return new k(t,r,c,b(t*r))}static normalizeZ(e){let t=r.invertBatch(e.map(e=>e.ez));return e.map((e,r)=>e.toAffine(t[r])).map(k.fromAffine)}_setWindowSize(e){this._WINDOW_SIZE=e,C.delete(this)}assertValidity(){let{a:e,d:r}=t;if(this.is0())throw Error("bad point: ZERO");let{ex:n,ey:i,ez:s,et:o}=this,a=b(n*n),l=b(i*i),c=b(s*s),u=b(c*c),h=b(a*e);if(b(c*b(h+l))!==b(u+b(r*b(a*l))))throw Error("bad point: equation left != right (1)");if(b(n*i)!==b(s*o))throw Error("bad point: equation left != right (2)")}equals(e){R(e);let{ex:t,ey:r,ez:n}=this,{ex:i,ey:s,ez:o}=e,a=b(t*o),l=b(i*n),c=b(r*o),u=b(s*n);return a===l&&c===u}is0(){return this.equals(k.ZERO)}negate(){return new k(b(-this.ex),this.ey,this.ez,b(-this.et))}double(){let{a:e}=t,{ex:r,ey:n,ez:i}=this,s=b(r*r),o=b(n*n),a=b(u*b(i*i)),l=b(e*s),c=r+n,h=b(b(c*c)-s-o),d=l+o,p=d-a,f=l-o,g=b(h*p),m=b(d*f),y=b(h*f);return new k(g,m,b(p*d),y)}add(e){R(e);let{a:r,d:n}=t,{ex:i,ey:s,ez:o,et:a}=this,{ex:c,ey:h,ez:d,et:p}=e;if(r===BigInt(-1)){let e=b((s-i)*(h+c)),t=b((s+i)*(h-c)),r=b(t-e);if(r===l)return this.double();let n=b(o*u*p),f=b(a*u*d),g=f+n,m=t+e,y=f-n,v=b(g*r),w=b(m*y),E=b(g*y);return new k(v,w,b(r*m),E)}let f=b(i*c),g=b(s*h),m=b(a*n*p),y=b(o*d),v=b((i+s)*(c+h)-f-g),w=y-m,E=y+m,S=b(g-r*f),A=b(v*w),I=b(E*S),_=b(v*S);return new k(A,I,b(w*E),_)}subtract(e){return this.add(e.negate())}wNAF(e){return B.wNAFCached(this,C,e,k.normalizeZ)}multiply(e){let{p:t,f:r}=this.wNAF(_(e,n));return k.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=T(e);return t===l?D:this.equals(D)||t===c?this:this.equals(P)?this.wNAF(t).p:B.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(m).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(e){let{ex:t,ey:n,ez:i}=this,s=this.is0();null==e&&(e=s?h:r.inv(i));let o=b(t*e),a=b(n*e),u=b(i*e);if(s)return{x:l,y:c};if(u!==c)throw Error("invZ was invalid");return{x:o,y:a}}clearCofactor(){let{h:e}=t;return e===c?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){let{d:i,a:s}=t,a=r.BYTES,u=(e=(0,o.ql)("pointHex",e,a)).slice(),h=e[a-1];u[a-1]=-129&h;let d=o.ty(u);d===l||(n?_(d,y):_(d,r.ORDER));let p=b(d*d),{isValid:f,value:g}=v(b(p-c),b(i*p-s));if(!f)throw Error("Point.fromHex: invalid y coordinate");let m=(g&c)===c,w=(128&h)!=0;if(!n&&g===l&&w)throw Error("Point.fromHex: x=0 and x_0=1");return w!==m&&(g=b(-g)),k.fromAffine({x:g,y:d})}static fromPrivateKey(e){return L(e).point}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=o.S5(t,r.BYTES);return n[n.length-1]|=e&c?128:0,n}toHex(){return o.ci(this.toRawBytes())}}k.BASE=new k(t.Gx,t.Gy,c,b(t.Gx*t.Gy)),k.ZERO=new k(l,c,c,l);let{BASE:P,ZERO:D}=k,B=(0,a.M)(k,8*g);function N(e){var t;return t=o.ty(e),(0,s.wQ)(t,n)}function L(e){e=(0,o.ql)("private key",e,g);let t=(0,o.ql)("hashed private key",p(e),2*g),r=w(t.slice(0,g)),n=t.slice(g,2*g),i=N(r),s=P.multiply(i),a=s.toRawBytes();return{head:r,prefix:n,scalar:i,point:s,pointBytes:a}}function x(e=new Uint8Array,...t){return N(p(E(o.eV(...t),(0,o.ql)("context",e),!!i)))}return P._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return L(e).pointBytes},sign:function(e,t,a={}){var l;e=(0,o.ql)("message",e),i&&(e=i(e));let{prefix:c,scalar:u,pointBytes:h}=L(t),d=x(a.context,c,e),p=P.multiply(d).toRawBytes(),f=(l=d+x(a.context,p,h,e)*u,(0,s.wQ)(l,n));T(f);let m=o.eV(p,o.S5(f,r.BYTES));return(0,o.ql)("result",m,2*g)},verify:function(e,t,n,s=d){let a,l,c;let{context:u,zip215:h}=s,p=r.BYTES;e=(0,o.ql)("signature",e,2*p),t=(0,o.ql)("message",t),i&&(t=i(t));let f=o.ty(e.slice(p,2*p));try{a=k.fromHex(n,h),l=k.fromHex(e.slice(0,p),h),c=P.multiplyUnsafe(f)}catch(e){return!1}if(!h&&a.isSmallOrder())return!1;let g=x(u,l.toRawBytes(),a.toRawBytes(),t);return l.add(a.multiplyUnsafe(g)).subtract(c).clearCofactor().equals(k.ZERO)},ExtendedPoint:k,utils:{getExtendedPublicKey:L,randomPrivateKey:()=>f(r.BYTES),precompute:(e=8,t=k.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(k);({...k,prehash:n.o});let D=function(e){let t=((0,o.FF)(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})),{P:r}=t,n=e=>(0,s.wQ)(e,r),i=t.montgomeryBits,a=Math.ceil(i/8),l=t.nByteLength,c=t.adjustScalarBytes||(e=>e),u=t.powPminus2||(e=>(0,s.sQ)(e,r-BigInt(2),r));function h(e,t,r){let i=n(e*(t-r));return[t=n(t-i),r=n(r+i)]}function d(e){if("bigint"==typeof e&&p<=e&&e=p;e--){let t=o>>e&f;y^=t,a=(r=h(y,a,c))[0],c=r[1],l=(r=h(y,l,m))[0],m=r[1],y=t;let i=a+l,u=n(i*i),d=a-l,p=n(d*d),b=u-p,v=c+m,w=n((c-m)*i),E=n(v*d),S=w+E,A=w-E;c=n(S*S),m=n(s*n(A*A)),a=n(u*p),l=n(b*(u+n(g*b)))}return a=(r=h(y,a,c))[0],c=r[1],l=(r=h(y,l,m))[0],m=r[1],n(a*u(l))}(function(e){let t=(0,o.ql)("u coordinate",e,a);return 32===l&&(t[31]&=127),(0,o.ty)(t)}(t),function(e){let t=(0,o.ql)("scalar",e),r=t.length;if(r!==a&&r!==l)throw Error(`Expected ${a} or ${l} bytes, got ${r}`);return(0,o.ty)(c(t))}(e));if(r===p)throw Error("Invalid private or public key received");return m(r)}let b=m(t.Gu);function v(e){return y(e,b)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(e,t)=>y(e,t),getPublicKey:e=>v(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:b}}({P:g,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{let{pow_p_5_8:t,b2:r}=_(e);return(0,s.wQ)((0,s.oA)(t,BigInt(3),g)*r,g)},adjustScalarBytes:T,randomBytes:i.O6}),B=(R.ORDER+BigInt(3))/BigInt(8);function N(e){if(!(e instanceof H))throw Error("RistrettoPoint expected")}R.pow(v,B),R.sqrt(R.neg(R.ONE)),R.ORDER,BigInt(5),BigInt(8),BigInt(486662),(0,s.DV)(R,R.neg(BigInt(486664)));let L=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),O=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),M=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),U=e=>C(b,e),F=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),K=e=>P.CURVE.Fp.create(bytesToNumberLE(e)&F);function V(e){let{d:t}=P.CURVE,r=P.CURVE.Fp.ORDER,n=P.CURVE.Fp.create,i=n(null*e*e),s=n((i+b)*O),o=BigInt(-1),a=n((o-t*i)*n(i+t)),{isValid:l,value:c}=C(s,a),u=n(c*e);isNegativeLE(u,r)||(u=n(-u)),l||(c=u),l||(o=i);let h=n(o*(i-b)*M-a),d=c*c,p=n((c+c)*a),f=n(h*L),g=n(b-d),m=n(b+d);return new P.ExtendedPoint(n(p*m),n(g*f),n(f*m),n(p*g))}class H{constructor(e){this.ep=e}static fromAffine(e){return new H(P.ExtendedPoint.fromAffine(e))}static hashToCurve(e){let t=V(K((e=ensureBytes("ristrettoHash",e,64)).slice(0,32))),r=V(K(e.slice(32,64)));return new H(t.add(r))}static fromHex(e){e=ensureBytes("ristrettoHex",e,32);let{a:t,d:r}=P.CURVE,n=P.CURVE.Fp.ORDER,i=P.CURVE.Fp.create,s="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",o=K(e);if(!equalBytes(numberToBytesLE(o,32),e)||isNegativeLE(o,n))throw Error(s);let a=i(o*o),l=i(b+t*a),c=i(b-t*a),u=i(l*l),h=i(c*c),d=i(t*r*u-h),{isValid:p,value:f}=U(i(d*h)),g=i(f*c),m=i(f*g*d),v=i((o+o)*g);isNegativeLE(v,n)&&(v=i(-v));let w=i(l*m),E=i(v*w);if(!p||isNegativeLE(E,n)||w===y)throw Error(s);return new H(new P.ExtendedPoint(v,w,b,E))}toRawBytes(){let e,{ex:t,ey:r,ez:n,et:i}=this.ep,s=P.CURVE.Fp.ORDER,o=P.CURVE.Fp.create,a=o(o(n+r)*o(n-r)),l=o(t*r),c=o(l*l),{value:u}=U(o(a*c)),h=o(u*a),d=o(u*l),p=o(h*d*i);if(isNegativeLE(i*p,s)){let n=o(null*r),i=o(null*t);t=n,r=i,e=o(h*x)}else e=d;isNegativeLE(t*p,s)&&(r=o(-r));let f=o((n-r)*e);return isNegativeLE(f,s)&&(f=o(-f)),numberToBytesLE(f,32)}toHex(){return bytesToHex(this.toRawBytes())}toString(){return this.toHex()}equals(e){N(e);let{ex:t,ey:r}=this.ep,{ex:n,ey:i}=e.ep,s=P.CURVE.Fp.create,o=s(t*i)===s(r*n),a=s(r*i)===s(t*n);return o||a}add(e){return N(e),new H(this.ep.add(e.ep))}subtract(e){return N(e),new H(this.ep.subtract(e.ep))}multiply(e){return new H(this.ep.multiply(e))}multiplyUnsafe(e){return new H(this.ep.multiplyUnsafe(e))}double(){return new H(this.ep.double())}negate(){return new H(this.ep.negate())}}},44458:function(e,t,r){"use strict";r.d(t,{Ee:function(){return b},NY:function(){return v},fC:function(){return y}});var n=r(22988),i=r(2265),s=r(98324),o=r(75137),a=r(1336),l=r(25171);let c="Avatar",[u,h]=(0,s.b)(c),[d,p]=u(c),f=(0,i.forwardRef)((e,t)=>{let{__scopeAvatar:r,...s}=e,[o,a]=(0,i.useState)("idle");return(0,i.createElement)(d,{scope:r,imageLoadingStatus:o,onImageLoadingStatusChange:a},(0,i.createElement)(l.WV.span,(0,n.Z)({},s,{ref:t})))}),g=(0,i.forwardRef)((e,t)=>{let{__scopeAvatar:r,src:s,onLoadingStatusChange:c=()=>{},...u}=e,h=p("AvatarImage",r),d=function(e){let[t,r]=(0,i.useState)("idle");return(0,a.b)(()=>{if(!e){r("error");return}let t=!0,n=new window.Image,i=e=>()=>{t&&r(e)};return r("loading"),n.onload=i("loaded"),n.onerror=i("error"),n.src=e,()=>{t=!1}},[e]),t}(s),f=(0,o.W)(e=>{c(e),h.onImageLoadingStatusChange(e)});return(0,a.b)(()=>{"idle"!==d&&f(d)},[d,f]),"loaded"===d?(0,i.createElement)(l.WV.img,(0,n.Z)({},u,{ref:t,src:s})):null}),m=(0,i.forwardRef)((e,t)=>{let{__scopeAvatar:r,delayMs:s,...o}=e,a=p("AvatarFallback",r),[c,u]=(0,i.useState)(void 0===s);return(0,i.useEffect)(()=>{if(void 0!==s){let e=window.setTimeout(()=>u(!0),s);return()=>window.clearTimeout(e)}},[s]),c&&"loaded"!==a.imageLoadingStatus?(0,i.createElement)(l.WV.span,(0,n.Z)({},o,{ref:t})):null}),y=f,b=g,v=m},9646:function(e,t,r){"use strict";r.d(t,{bU:function(){return S},fC:function(){return E}});var n=r(22988),i=r(2265),s=r(78149),o=r(1584),a=r(98324),l=r(91715),c=r(47250),u=r(75238),h=r(25171);let d="Switch",[p,f]=(0,a.b)(d),[g,m]=p(d),y=(0,i.forwardRef)((e,t)=>{let{__scopeSwitch:r,name:a,checked:c,defaultChecked:u,required:d,disabled:p,value:f="on",onCheckedChange:m,...y}=e,[b,E]=(0,i.useState)(null),S=(0,o.e)(t,e=>E(e)),A=(0,i.useRef)(!1),I=!b||!!b.closest("form"),[_=!1,T]=(0,l.T)({prop:c,defaultProp:u,onChange:m});return(0,i.createElement)(g,{scope:r,checked:_,disabled:p},(0,i.createElement)(h.WV.button,(0,n.Z)({type:"button",role:"switch","aria-checked":_,"aria-required":d,"data-state":w(_),"data-disabled":p?"":void 0,disabled:p,value:f},y,{ref:S,onClick:(0,s.M)(e.onClick,e=>{T(e=>!e),I&&(A.current=e.isPropagationStopped(),A.current||e.stopPropagation())})})),I&&(0,i.createElement)(v,{control:b,bubbles:!A.current,name:a,value:f,checked:_,required:d,disabled:p,style:{transform:"translateX(-100%)"}}))}),b=(0,i.forwardRef)((e,t)=>{let{__scopeSwitch:r,...s}=e,o=m("SwitchThumb",r);return(0,i.createElement)(h.WV.span,(0,n.Z)({"data-state":w(o.checked),"data-disabled":o.disabled?"":void 0},s,{ref:t}))}),v=e=>{let{control:t,checked:r,bubbles:s=!0,...o}=e,a=(0,i.useRef)(null),l=(0,c.D)(r),h=(0,u.t)(t);return(0,i.useEffect)(()=>{let e=a.current,t=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"checked").set;if(l!==r&&t){let n=new Event("click",{bubbles:s});t.call(e,r),e.dispatchEvent(n)}},[l,r,s]),(0,i.createElement)("input",(0,n.Z)({type:"checkbox","aria-hidden":!0,defaultChecked:r},o,{tabIndex:-1,ref:a,style:{...e.style,...h,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function w(e){return e?"checked":"unchecked"}let E=y,S=b},97540:function(e,t,r){"use strict";r.d(t,{p:function(){return a}});var n=r(33126),i=r(85419),s=r(75354),o=r(47651);class a{multicodec;components;log;pubsubTopics;options;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n,i){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.options=i,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new o.a(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}get peerStore(){return this.components.peerStore}async allPeers(){return(0,i.RB)(this.peerStore,[this.multicodec])}async connectedPeers(){return(await this.allPeers()).filter(e=>this.components.connectionManager.getConnections(e.id).length>0)}async getPeers({numPeers:e,maxBootstrapPeers:t}={maxBootstrapPeers:1,numPeers:0}){let r=function(e,t,r){let n=e.filter(e=>e.tags.has(s.$G.BOOTSTRAP)).slice(0,r);t>0&&t!e.tags.has(s.$G.BOOTSTRAP));if(0===t)return[...n,...i];let o=[...n];for(;o.length0;){let e=Math.floor(Math.random()*i.length),t=i.splice(e,1)[0];o.push(t)}return o}(await (0,i._4)(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?(0,n.Ao)(this.options.shardInfo).shardInfo:void 0),e,t),o=await (0,i.tf)(this.peerStore,r);return 0===o.length&&this.log.warn("No peers found. Ensure you have a connection to the network."),o.length{this.log.error(`Failed to prepare a new stream for ${e.id.toString()}`)});this.streamPool.set(e.id.toString(),t)}handlePeerUpdateStreamPool=e=>{let t=e.detail.peer;t.protocols.includes(this.multicodec)&&(this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareNewStream(t))}}},18976:function(e,t,r){"use strict";let n,i;r.d(t,{Qy:function(){return m},Lk:function(){return rF},C0:function(){return r5},PZ:function(){return r0}});var s,o,a,l,c,u,h,d,p=r(85931),f=r(5846),g=r(33126);let m={TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im"},y="bootstrap",b={store:2,filter:1,lightPush:1};var v=r(48215),w=r(95856),E=r.t(w,2);/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */let S=BigInt(0),A=BigInt(1),I=BigInt(2),_=BigInt(3),T=BigInt(8),C=Object.freeze({a:S,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:A,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),R=(e,t)=>(e+t/I)/t,k={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){let{n:t}=C,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-A*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=BigInt("0x100000000000000000000000000000000"),o=R(r*e,t),a=R(-n*e,t),l=Z(e-o*r-a*i,t),c=Z(-o*n-a*r,t),u=l>s,h=c>s;if(u&&(l=t-l),h&&(c=t-c),l>s||c>s)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:u,k1:l,k2neg:h,k2:c}}};function P(e){let{a:t,b:r}=C,n=Z(e*e),i=Z(n*e);return Z(i+t*e+r)}let D=C.a===S;class B extends Error{constructor(e){super(e)}}function N(e){if(!(e instanceof L))throw TypeError("JacobianPoint expected")}class L{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof M))throw TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(M.ZERO)?L.ZERO:new L(e.x,e.y,A)}static toAffineBatch(e){let t=function(e,t=C.P){let r=Array(e.length),n=et(e.reduce((e,n,i)=>n===S?e:(r[i]=e,Z(e*n,t)),A),t);return e.reduceRight((e,n,i)=>n===S?e:(r[i]=Z(e*r[i],t),Z(e*n,t)),n),r}(e.map(e=>e.z));return e.map((e,r)=>e.toAffine(t[r]))}static normalizeZ(e){return L.toAffineBatch(e).map(L.fromAffine)}equals(e){N(e);let{x:t,y:r,z:n}=this,{x:i,y:s,z:o}=e,a=Z(n*n),l=Z(o*o),c=Z(t*l),u=Z(i*a),h=Z(Z(r*o)*l),d=Z(Z(s*n)*a);return c===u&&h===d}negate(){return new L(this.x,Z(-this.y),this.z)}double(){let{x:e,y:t,z:r}=this,n=Z(e*e),i=Z(t*t),s=Z(i*i),o=e+i,a=Z(I*(Z(o*o)-n-s)),l=Z(_*n),c=Z(l*l),u=Z(c-I*a),h=Z(l*(a-u)-T*s);return new L(u,h,Z(I*t*r))}add(e){N(e);let{x:t,y:r,z:n}=this,{x:i,y:s,z:o}=e;if(i===S||s===S)return this;if(t===S||r===S)return e;let a=Z(n*n),l=Z(o*o),c=Z(t*l),u=Z(i*a),h=Z(Z(r*o)*l),d=Z(Z(s*n)*a),p=Z(u-c),f=Z(d-h);if(p===S)return f===S?this.double():L.ZERO;let g=Z(p*p),m=Z(p*g),y=Z(c*g),b=Z(f*f-m-I*y),v=Z(f*(y-b)-h*m);return new L(b,v,Z(n*o*p))}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=L.ZERO;if("bigint"==typeof e&&e===S)return t;let r=X(e);if(r===A)return this;if(!D){let e=t,n=this;for(;r>S;)r&A&&(e=e.add(n)),n=n.double(),r>>=A;return e}let{k1neg:n,k1:i,k2neg:s,k2:o}=k.splitScalar(r),a=t,l=t,c=this;for(;i>S||o>S;)i&A&&(a=a.add(c)),o&A&&(l=l.add(c)),c=c.double(),i>>=A,o>>=A;return n&&(a=a.negate()),s&&(l=l.negate()),l=new L(Z(l.x*k.beta),l.y,l.z),a.add(l)}precomputeWindow(e){let t=D?128/e+1:256/e+1,r=[],n=this,i=n;for(let s=0;s>=u,o>a&&(o-=c,e+=A);let h=r+Math.abs(o)-1,d=t%2!=0,p=o<0;0===o?s=s.add(x(d,n[r])):i=i.add(x(p,n[h]))}return{p:i,f:s}}multiply(e,t){let r,n,i=X(e);if(D){let{k1neg:e,k1:s,k2neg:o,k2:a}=k.splitScalar(i),{p:l,f:c}=this.wNAF(s,t),{p:u,f:h}=this.wNAF(a,t);l=x(e,l),u=new L(Z((u=x(o,u)).x*k.beta),u.y,u.z),r=l.add(u),n=c.add(h)}else{let{p:e,f:s}=this.wNAF(i,t);r=e,n=s}return L.normalizeZ([r,n])[0]}toAffine(e){let{x:t,y:r,z:n}=this,i=this.equals(L.ZERO);null==e&&(e=i?T:et(n));let s=e,o=Z(s*s),a=Z(o*s),l=Z(t*o),c=Z(r*a),u=Z(n*s);if(i)return M.ZERO;if(u!==A)throw Error("invZ was invalid");return new M(l,c)}}function x(e,t){let r=t.negate();return e?r:t}L.BASE=new L(C.Gx,C.Gy,A),L.ZERO=new L(S,A,S);let O=new WeakMap;class M{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,O.delete(this)}hasEvenY(){return this.y%I===S}static fromCompressedHex(e){let t=32===e.length,r=Q(t?e:e.subarray(1));if(!es(r))throw Error("Point is not on curve");let n=function(e){let{P:t}=C,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),l=e*e*e%t,c=l*l*e%t,u=ee(c,_)*c%t,h=ee(u,_)*c%t,d=ee(h,I)*l%t,p=ee(d,n)*d%t,f=ee(p,i)*p%t,g=ee(f,o)*f%t,m=ee(g,a)*g%t,y=ee(m,o)*f%t,b=ee(y,_)*c%t,v=ee(b,s)*p%t,w=ee(v,r)*l%t,E=ee(w,I);if(E*E%t!==e)throw Error("Cannot find square root");return E}(P(r)),i=(n&A)===A;t?i&&(n=Z(-n)):(1&e[0])==1!==i&&(n=Z(-n));let s=new M(r,n);return s.assertValidity(),s}static fromUncompressedHex(e){let t=new M(Q(e.subarray(1,33)),Q(e.subarray(33,65)));return t.assertValidity(),t}static fromHex(e){let t=J(e),r=t.length,n=t[0];if(32===r||33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return M.BASE.multiply(eo(e))}static fromSignature(e,t,r){let{r:n,s:i}=ea(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");let s=er(J(e)),{n:o}=C,a=2===r||3===r?n+o:n,l=et(a,o),c=Z(-s*l,o),u=Z(i*l,o),h=1&r?"03":"02",d=M.fromHex(h+z(a)),p=M.BASE.multiplyAndAddUnsafe(d,c,u);if(!p)throw Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Y(this.toHex(e))}toHex(e=!1){let t=z(this.x);if(!e)return`04${t}${z(this.y)}`;{let e=this.hasEvenY()?"02":"03";return`${e}${t}`}}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:r}=this;if(!es(t)||!es(r))throw Error(e);let n=Z(r*r);if(Z(n-P(t))!==S)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new M(this.x,Z(-this.y))}double(){return L.fromAffine(this).double().toAffine()}add(e){return L.fromAffine(this).add(L.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return L.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){let n=L.fromAffine(this),i=t===S||t===A||this!==M.BASE?n.multiplyUnsafe(t):n.multiply(t),s=L.fromAffine(e).multiplyUnsafe(r),o=i.add(s);return o.equals(L.ZERO)?void 0:o.toAffine()}}function U(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function F(e){if(e.length<2||2!==e[0])throw Error(`Invalid signature integer tag: ${$(e)}`);let t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:Q(r),left:e.subarray(t+2)}}M.BASE=new M(C.Gx,C.Gy),M.ZERO=new M(S,S);class K{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw TypeError(`${r}: Expected string or Uint8Array`);let n=t?$(e):e;if(128!==n.length)throw Error(`${r}: Expected 64-byte hex`);return new K(W(n.slice(0,64)),W(n.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw TypeError("Signature.fromDER: Expected string or Uint8Array");let{r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error(`Invalid signature tag: ${$(e)}`);if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");let{data:t,left:r}=F(e.subarray(2)),{data:n,left:i}=F(r);if(i.length)throw Error(`Invalid signature: left bytes after parsing: ${$(i)}`);return{r:t,s:n}}(t?e:Y(e));return new K(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!ei(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!ei(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=C.n>>A;return this.s>e}normalizeS(){return this.hasHighS()?new K(this.r,Z(-this.s,C.n)):this}toDERRawBytes(){return Y(this.toDERHex())}toDERHex(){let e=U(G(this.s)),t=U(G(this.r)),r=e.length/2,n=t.length/2,i=G(r),s=G(n),o=G(n+r+4);return`30${o}02${s}${t}02${i}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Y(this.toCompactHex())}toCompactHex(){return z(this.r)+z(this.s)}}function V(...e){if(!e.every(e=>e instanceof Uint8Array))throw Error("Uint8Array list expected");if(1===e.length)return e[0];let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));for(let r=0,n=0;rt.toString(16).padStart(2,"0"));function $(e){if(!(e instanceof Uint8Array))throw Error("Expected Uint8Array");let t="";for(let r=0;r0)return BigInt(e);if("bigint"==typeof e&&ei(e))return e;throw TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Z(e,t=C.P){let r=e%t;return r>=S?r:t+r}function ee(e,t){let{P:r}=C,n=e;for(;t-- >S;)n*=n,n%=r;return n}function et(e,t=C.P){if(e===S||t<=S)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Z(e,t),n=t,i=S,s=A,o=A,a=S;for(;r!==S;){let e=n/r,t=n%r,l=i-o*e,c=s-a*e;n=r,r=t,i=o,s=a,o=l,a=c}if(n!==A)throw Error("invert: does not exist");return Z(i,t)}function er(e,t=!1){let r=function(e){let t=8*e.length-256,r=Q(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;let{n}=C;return r>=n?r-n:r}class en{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return ep.hmacSha256(this.k,...e)}hmacSync(...e){return i(this.k,...e)}checkSync(){if("function"!=typeof i)throw new B("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=W(e)}else if(e instanceof Uint8Array){if(32!==e.length)throw Error("Expected 32 bytes of private key");t=Q(e)}else throw TypeError("Expected valid private key");if(!ei(t))throw Error("Expected private key: 0 < key < n");return t}function ea(e){if(e instanceof K)return e.assertValidity(),e;try{return K.fromDER(e)}catch(t){return K.fromCompact(e)}}function el(e){return Q(e.length>32?e.slice(0,32):e)}async function ec(e,t,r={}){let n;let{seed:i,m:s,d:o}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);let n=J(e),i=eo(t),s=[j(i),function(e){let t=el(e),r=Z(t,C.n);return j(r{if((e=J(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");return j(Z(Q(e),C.n-A)+A)},randomBytes:(e=32)=>{if(eh.web)return eh.web.getRandomValues(new Uint8Array(e));if(eh.node){let{randomBytes:t}=eh.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>ep.hashToPrivateKey(ep.randomBytes(40)),precompute(e=8,t=M.BASE){let r=t===M.BASE?t:new M(t.x,t.y);return r._setWindowSize(e),r.multiply(_),r},sha256:async(...e)=>{if(eh.web)return new Uint8Array(await eh.web.subtle.digest("SHA-256",V(...e)));if(eh.node){let{createHash:t}=eh.node,r=t("sha256");return e.forEach(e=>r.update(e)),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(eh.web){let r=await eh.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=V(...t);return new Uint8Array(await eh.web.subtle.sign("HMAC",r,n))}if(eh.node){let{createHmac:r}=eh.node,n=r("sha256",e);return t.forEach(e=>n.update(e)),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=ed[e];if(void 0===r){let t=await ep.sha256(Uint8Array.from(e,e=>e.charCodeAt(0)));r=V(t,t),ed[e]=r}return ep.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof n)throw new B("sha256Sync is undefined, you need to set it");let r=ed[e];if(void 0===r){let t=n(Uint8Array.from(e,e=>e.charCodeAt(0)));r=V(t,t),ed[e]=r}return n(r,...t)},_JacobianPoint:L};Object.defineProperties(ep,{sha256Sync:{configurable:!1,get:()=>n,set(e){n||(n=e)}},hmacSha256Sync:{configurable:!1,get:()=>i,set(e){i||(i=e)}}});var ef=r(83524);function eg(e){return new Uint8Array(ef.keccak256.arrayBuffer(e))}function em(e,t,r){try{let n=K.fromCompact(e.slice(0,64));return function(e,t,r,n=eu){let i,s;try{i=ea(e),t=J(t)}catch(e){return!1}let{r:o,s:a}=i;if(n.strict&&i.hasHighS())return!1;let l=er(t);try{s=r instanceof M?(r.assertValidity(),r):M.fromHex(r)}catch(e){return!1}let{n:c}=C,u=et(a,c),h=Z(l*u,c),d=Z(o*u,c),p=M.BASE.multiplyAndAddUnsafe(s,h,d);return!!p&&Z(p.x,c)===o}(n,t,r)}catch{return!1}}let ey="Invalid record id";var eb=r(40914),ev=r(88695),ew=r(36408),eE=r(65301);function eS(e){let t=new Uint8Array(e.reduce((e,t)=>e+2+t.bytes.length,0)),r=new DataView(t.buffer),n=0;return e.forEach(e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");r.setUint16(n,e.bytes.length),n+=2,t.set(e.bytes,n),n+=e.bytes.length}),t}class eA extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){let e=this.get("id");if(!e)throw Error("id not found.");return(0,v.Md)(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(ey)}get rs(){let e=this.get("rs");if(e)return(0,g.Ix)(e)}get rsv(){let e=this.get("rsv");if(e)return(0,g.Ix)(e)}get ip(){return eI(this,"ip","ip4")}set ip(e){eT(this,"ip","ip4",e)}get tcp(){return e_(this,"tcp","tcp")}set tcp(e){eC(this,"tcp","tcp",e)}get udp(){return e_(this,"udp","udp")}set udp(e){eC(this,"udp","udp",e)}get ip6(){return eI(this,"ip6","ip6")}set ip6(e){eT(this,"ip6","ip6",e)}get tcp6(){return e_(this,"tcp6","tcp")}set tcp6(e){eC(this,"tcp6","tcp",e)}get udp6(){return e_(this,"udp6","udp")}set udp6(e){eC(this,"udp6","udp",e)}get multiaddrs(){let e=this.get("multiaddrs");if(e)return function(e){let t=[],r=0;for(;r>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){eR(this,"waku2",e,e=>{let t;return new Uint8Array([(t=0,e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t)])})}}function eI(e,t,r){let n=e.get(t);if(n)return(0,ev.xV)(r,n)}function e_(e,t,r){let n=e.get(t);if(n)return Number((0,ev.xV)(r,n))}function eT(e,t,r,n){eR(e,t,n,ev.Fm.bind({},r))}function eC(e,t,r,n){eT(e,t,r,n?.toString(10))}function eR(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function ek(e,t){return ec(eg(t),e,{der:!1})}let eP=new g.Yd("enr");(s=c||(c={})).TCP="tcp",s.UDP="udp",(o=u||(u={})).TCP4="tcp4",o.UDP4="udp4",o.TCP6="tcp6",o.UDP6="udp6";class eD extends eA{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){let n=new eD(e,t,r);try{let e=n.publicKey;e&&(n.peerId=await function(e){let t=new ew.xO.secp256k1.Secp256k1PublicKey(e);return(0,eE.y5)(t.bytes,void 0)}(e))}catch(e){eP.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){let t=M.fromHex(e).toRawBytes(!1);return(0,v.ci)(eg(t.slice(1)))}(this.publicKey):void 0;throw Error(ey)}getLocationMultiaddr=(function e(t,r){let n;switch(r){case"udp":return e(t,"udp4")||e(t,"udp6");case"tcp":return e(t,"tcp4")||e(t,"tcp6")}let i=r.endsWith("6"),s=t.get(i?"ip6":"ip");if(!s)return;let o=r.slice(0,3);switch(o){case"udp":n=i?t.get("udp6"):t.get("udp");break;case"tcp":n=i?t.get("tcp6"):t.get("tcp");break;default:return}if(n){var a,l;return a=i?"ip6":"ip4",l=n,(0,eb.HM)("/"+a+"/"+(0,ev.xV)(a,s)).encapsulate((0,eb.HM)("/"+o+"/"+(0,ev.xV)(o,l)))}}).bind({},this);get shardInfo(){return this.rs&&this.rsv&&eP.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){let t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");let r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){let e=[];for(let t of Object.values(u)){let r=this.getLocationMultiaddr(t);r&&e.push(r)}let t=this.multiaddrs??[];return e.concat(t).map(e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e)}get peerInfo(){let e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){let t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){let e=this.peerId;return this.multiaddrs.map(t=>t.encapsulate(`/p2p/${e.toString()}`))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(ey);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return em(t,eg(e),this.publicKey)}async sign(e,t){if("v4"===this.id)this.signature=await ek(t,e);else throw Error(ey);return this.signature}}let eB=!1,eN=!1,eL={debug:1,default:2,info:2,warning:3,error:4,off:5},ex=eL.default,eO=null,eM=function(){try{let e=[];if(["NFD","NFC","NFKD","NFKC"].forEach(t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}}),e.length)throw Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw Error("broken implementation")}catch(e){return e.message}return null}();(a=h||(h={})).DEBUG="DEBUG",a.INFO="INFO",a.WARNING="WARNING",a.ERROR="ERROR",a.OFF="OFF",(l=d||(d={})).UNKNOWN_ERROR="UNKNOWN_ERROR",l.NOT_IMPLEMENTED="NOT_IMPLEMENTED",l.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",l.NETWORK_ERROR="NETWORK_ERROR",l.SERVER_ERROR="SERVER_ERROR",l.TIMEOUT="TIMEOUT",l.BUFFER_OVERRUN="BUFFER_OVERRUN",l.NUMERIC_FAULT="NUMERIC_FAULT",l.MISSING_NEW="MISSING_NEW",l.INVALID_ARGUMENT="INVALID_ARGUMENT",l.MISSING_ARGUMENT="MISSING_ARGUMENT",l.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",l.CALL_EXCEPTION="CALL_EXCEPTION",l.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",l.NONCE_EXPIRED="NONCE_EXPIRED",l.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",l.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",l.TRANSACTION_REPLACED="TRANSACTION_REPLACED",l.ACTION_REJECTED="ACTION_REJECTED";let eU="0123456789abcdef";class eF{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){let r=e.toLowerCase();null==eL[r]&&this.throwArgumentError("invalid log level name","logLevel",e),ex>eL[r]||console.log.apply(console,t)}debug(...e){this._log(eF.levels.DEBUG,e)}info(...e){this._log(eF.levels.INFO,e)}warn(...e){this._log(eF.levels.WARNING,e)}makeError(e,t,r){if(eN)return this.makeError("censored error",t,{});t||(t=eF.errors.UNKNOWN_ERROR),r||(r={});let n=[];Object.keys(r).forEach(e=>{let t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e>4]+eU[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);let i=e,s="";switch(t){case d.NUMERIC_FAULT:{s="NUMERIC_FAULT";let t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case d.CALL_EXCEPTION:case d.INSUFFICIENT_FUNDS:case d.MISSING_NEW:case d.NONCE_EXPIRED:case d.REPLACEMENT_UNDERPRICED:case d.TRANSACTION_REPLACED:case d.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),n.length&&(e+=" ("+n.join(", ")+")");let o=Error(e);return o.reason=i,o.code=t,Object.keys(r).forEach(function(e){o[e]=r[e]}),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,eF.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),eM&&this.throwError("platform missing String.prototype.normalize",eF.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:eM})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,eF.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,eF.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,eF.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){(e===Object||null==e)&&this.throwError("missing new",eF.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",eF.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||null==e)&&this.throwError("missing new",eF.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return eO||(eO=new eF("logger/5.7.0")),eO}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",eF.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),eB){if(!e)return;this.globalLogger().throwError("error censorship permanent",eF.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}eN=!!e,eB=!!t}static setLogLevel(e){let t=eL[e.toLowerCase()];if(null==t){eF.globalLogger().warn("invalid log level - "+e);return}ex=t}static from(e){return new eF(e)}}eF.errors=d,eF.levels=h;let eK=new eF("bytes/5.7.0");function eV(e){return!!e.toHexString}function eH(e){return e.slice||(e.slice=function(){let t=Array.prototype.slice.call(arguments);return eH(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function e$(e){return"number"==typeof e&&e==e&&e%1==0}function eq(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e||!e$(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function ez(e,t){if(t||(t={}),"number"==typeof e){eK.checkSafeUint53(e,"invalid arrayify value");let t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),eH(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),eV(e)&&(e=e.toHexString()),ej(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":eK.throwArgumentError("hex data is odd-length","value",e));let n=[];for(let e=0;e>4]+eG[15&n]}return t}return eK.throwArgumentError("invalid hexlify value","value",e)}let eY=new eF("rlp/5.7.0");function eQ(e){let t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function eJ(e,t,r){let n=0;for(let i=0;it+1+n&&eY.throwError("child data too short",eF.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:i}}function eZ(e,t){if(0===e.length&&eY.throwError("data too short",eF.errors.BUFFER_OVERRUN,{}),e[t]>=248){let r=e[t]-247;t+1+r>e.length&&eY.throwError("data short segment too short",eF.errors.BUFFER_OVERRUN,{});let n=eJ(e,t+1,r);return t+1+r+n>e.length&&eY.throwError("data long segment too short",eF.errors.BUFFER_OVERRUN,{}),eX(e,t,t+1+r,r+n)}if(e[t]>=192){let r=e[t]-192;return t+1+r>e.length&&eY.throwError("data array too short",eF.errors.BUFFER_OVERRUN,{}),eX(e,t,t+1,r)}if(e[t]>=184){let r=e[t]-183;t+1+r>e.length&&eY.throwError("data array too short",eF.errors.BUFFER_OVERRUN,{});let n=eJ(e,t+1,r);t+1+r+n>e.length&&eY.throwError("data array too short",eF.errors.BUFFER_OVERRUN,{});let i=eW(e.slice(t+1+r,t+1+r+n));return{consumed:1+r+n,result:i}}if(e[t]>=128){let r=e[t]-128;t+1+r>e.length&&eY.throwError("data too short",eF.errors.BUFFER_OVERRUN,{});let n=eW(e.slice(t+1,t+1+r));return{consumed:1+r,result:n}}return{consumed:1,result:eW(e[t])}}var e0=r(60565);let e1=new g.Yd("enr:decoder");class e2{static fromString(e){if(!e.startsWith(eD.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${eD.RECORD_PREFIX}'`);return e2.fromRLP((0,e0.m)(e.slice(4),"base64url"))}static fromRLP(e){return e3((function(e){let t=ez(e),r=eZ(t,0);return r.consumed!==t.length&&eY.throwArgumentError("invalid rlp data","data",e),r.result})(e).map(v.nr))}}async function e3(e){let{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");let[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),i={};for(let e=0;ee4.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);let n=e.length,i=0;for(let s=0;s(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},e8={name:"v6",size:16,isFormat:e=>e.length>0&&e6.test(e),encode(e,t,r){let n=(r=~~r)+16,i=-1,s=0,o=0,a=!0,l=!1;t=t||new Uint8Array(r+16);for(let c=0;c>8),r=97?u-=87:u>=65?u-=55:(u-=48,o=10*o+u),s=(s<<4)+u)}if(!1===a)!0===l?(r>8),r=i+2;e--)t[e]=t[e-2];t[i]=0,t[i+1]=0,i=r}if(i!==r&&-1!==i)for(r>n-2&&(r=n-2);n>i;)t[--n]=ri?t[--r]:0;else for(;r=56320?t+=3:(64512&e.charCodeAt(s))!=56320?t+=3:(n=s,t+=4)}}return t}function ts(e,t,r){let n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(ti(e)+r));let i=r;for(let r=0;r>6,t[i++]=128|63&s;else if((63488&s)!=55296)t[i++]=224|(61440&s)>>12,t[i++]=128|(4032&s)>>6,t[i++]=128|63&s;else{let o=r+1;if(o===n||s>=56320)t[i++]=239,t[i++]=191,t[i++]=189;else{let n=e.charCodeAt(o);(64512&n)!=56320?(t[i++]=239,t[i++]=191,t[i++]=189):(r=o,s=65536|(1023&s)<<10|1023&n,t[i++]=240|(1835008&s)>>18,t[i++]=128|(258048&s)>>12,t[i++]=128|(4032&s)>>6,t[i++]=128|63&s)}}}return ts.bytes=i-r,t}function to(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let i=t;i191&&r<224?t=(31&r)<<6|63&e[i++]:r>239&&r<365?(n+=String.fromCharCode(55296|(t=((7&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536)>>10&1023),t=56320|1023&t):t=(15&r)<<12|(63&e[i++])<<6|63&e[i++],n+=String.fromCharCode(t)}return to.bytes=r-t,n}ts.bytes=0,to.bytes=0;let ta=e=>e instanceof Uint8Array;function tl(e){return"string"==typeof e?ti(e):e.byteLength}function tc(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):ts(e)}function tu(e,t,r){if("string"!=typeof t)throw Error("unknown input type");return ts(t,e,r),ts.bytes}let th=(e,t)=>16777216*e[t]+65536*e[t+1]+256*e[t+2]+e[t+3],td=(e,t)=>e[t]<<8|e[t+1],tp=(e,t,r)=>(t=+t,e[r+3]=t,t>>>=8,e[r+2]=t,t>>>=8,e[r+1]=t,t>>>=8,e[r]=t,r+4),tf=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function tg(e,t,r,n,i){return(r<0&&(n-=r,r=0),n<0&&(n=0),i<0)?new Uint8Array(0):r>=t.length||n>=i?0:function(e,t,r,n,i){i-n>t.length-r&&(i=n+t.length-r);let s=i-n,o=e.length-n;return s>o&&(s=o),(0!==n||ie)}}let ty=tm({encode(e,t,r){t||(t=new Uint8Array(ty.encodingLength(e))),r||(r=0);let n=r,i=e.replace(/^\.|\.$/gm,"");if(i.length){let e=i.split(".");for(let n=0;n=e.length)throw Error("Cannot decode name (buffer overflow)");let a=e[t++];if(s+=o?0:1,0===a)break;if((192&a)==0){if(t+a>e.length)throw Error("Cannot decode name (buffer overflow)");if((i+=a+1)>254)throw Error("Cannot decode name (name too long)");r.push(to(e,t,t+a)),t+=a,s+=o?0:a}else if((192&a)==192){if(t+1>e.length)throw Error("Cannot decode name (buffer overflow)");let r=td(e,t-1)-49152;if(r>=n)throw Error("Cannot decode name (bad pointer)");t=r,n=r,s+=o?0:1,o=!0}else throw Error("Cannot decode name (bad label)")}return ty.decode.bytes=s,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:tl(e.replace(/^\.|\.$/gm,""))+2}),tb=tm({encode(e,t,r){t||(t=new Uint8Array(tb.encodingLength(e))),r||(r=0);let n=tu(t,e,r+1);return t[r]=n,tb.encode.bytes=n+1,t},decode(e,t){t||(t=0);let r=e[t],n=to(e,t+1,t+1+r);return tb.decode.bytes=r+1,n},encodingLength:e=>tl(e)+1}),tv=tm({bytes:12,encode(e,t,r){t||(t=new Uint8Array(tv.encodingLength(e))),r||(r=0);let n=32767&(e.flags||0),i="response"===e.type?32768:0;return tf(t,e.id||0,r),tf(t,n|i,r+2),tf(t,e.questions.length,r+4),tf(t,e.answers.length,r+6),tf(t,e.authorities.length,r+8),tf(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw Error("Header must be 12 bytes");let r=td(e,t+2);return{id:td(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:(r>>15&1)==1,opcode:function(e){switch(e){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+e}(r>>11&15),flag_aa:(r>>10&1)==1,flag_tc:(r>>9&1)==1,flag_rd:(r>>8&1)==1,flag_ra:(r>>7&1)==1,flag_z:(r>>6&1)==1,flag_ad:(r>>5&1)==1,flag_cd:(r>>4&1)==1,rcode:function(e){switch(e){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+e}(15&r),questions:Array(td(e,t+4)),answers:Array(td(e,t+6)),authorities:Array(td(e,t+8)),additionals:Array(td(e,t+10))}},encodingLength:()=>12}),tw=tm({encode(e,t,r){t||(t=new Uint8Array(tw.encodingLength(e))),r||(r=0);let n=e.length;return tf(t,n,r),tg(e,t,r+2,0,n),tw.encode.bytes=n+2,t},decode(e,t){t||(t=0);let r=td(e,t),n=e.slice(t+2,t+2+r);return tw.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),tE=tm({encode:(e,t,r)=>(t||(t=new Uint8Array(tE.encodingLength(e))),r||(r=0),ty.encode(e,t,r+2),tf(t,ty.encode.bytes,r),tE.encode.bytes=ty.encode.bytes+2,t),decode(e,t){t||(t=0);let r=td(e,t),n=ty.decode(e,t+2);return tE.decode.bytes=r+2,n},encodingLength:e=>ty.encodingLength(e)+2}),tS=tm({encode(e,t,r){t||(t=new Uint8Array(tS.encodingLength(e))),r||(r=0);let n=r;return r+=2,ty.encode(e.mname,t,r),r+=ty.encode.bytes,ty.encode(e.rname,t,r),r+=ty.encode.bytes,tp(t,e.serial||0,r),r+=4,tp(t,e.refresh||0,r),r+=4,tp(t,e.retry||0,r),r+=4,tp(t,e.expire||0,r),r+=4,tp(t,e.minimum||0,r),r+=4,tf(t,r-n-2,n),tS.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.mname=ty.decode(e,t),t+=ty.decode.bytes,n.rname=ty.decode(e,t),t+=ty.decode.bytes,n.serial=th(e,t),t+=4,n.refresh=th(e,t),t+=4,n.retry=th(e,t),t+=4,n.expire=th(e,t),t+=4,n.minimum=th(e,t),t+=4,tS.decode.bytes=t-r,n},encodingLength:e=>22+ty.encodingLength(e.mname)+ty.encodingLength(e.rname)}),tA=tm({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t0;){let r=e[t++];if(--ne?(ta(e)?e.length:tl(e))+2:2}),t_=tm({encode(e,t,r){t||(t=new Uint8Array(t_.encodingLength(e))),r||(r=0);let n=r;return r+=2,tb.encode(e.cpu,t,r),r+=tb.encode.bytes,tb.encode(e.os,t,r),r+=tb.encode.bytes,tf(t,r-n-2,n),t_.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.cpu=tb.decode(e,t),t+=tb.decode.bytes,n.os=tb.decode(e,t),t+=tb.decode.bytes,t_.decode.bytes=t-r,n},encodingLength:e=>tb.encodingLength(e.cpu)+tb.encodingLength(e.os)+2}),tT=tm({encode:(e,t,r)=>(t||(t=new Uint8Array(tT.encodingLength(e))),r||(r=0),ty.encode(e,t,r+2),tf(t,ty.encode.bytes,r),tT.encode.bytes=ty.encode.bytes+2,t),decode(e,t){t||(t=0);let r=ty.decode(e,t+2);return tT.decode.bytes=ty.decode.bytes+2,r},encodingLength:e=>ty.encodingLength(e)+2}),tC=tm({encode(e,t,r){t||(t=new Uint8Array(tC.encodingLength(e))),r||(r=0),tf(t,e.priority||0,r+2),tf(t,e.weight||0,r+4),tf(t,e.port||0,r+6),ty.encode(e.target,t,r+8);let n=ty.encode.bytes+6;return tf(t,n,r),tC.encode.bytes=n+2,t},decode(e,t){t||(t=0);let r=td(e,t),n={};return n.priority=td(e,t+2),n.weight=td(e,t+4),n.port=td(e,t+6),n.target=ty.decode(e,t+8),tC.decode.bytes=r+2,n},encodingLength:e=>8+ty.encodingLength(e.target)}),tR=tm({encode(e,t,r){let n=tR.encodingLength(e);return t||(t=new Uint8Array(tR.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=tR.ISSUER_CRITICAL),tf(t,n-2,r),t[r+=2]=e.flags||0,r+=1,tb.encode(e.tag,t,r),r+=tb.encode.bytes,tu(t,e.value,r),r+=tl(e.value),tR.encode.bytes=n,t},decode(e,t){t||(t=0);let r=td(e,t),n=t+=2,i={};return i.flags=e[t],t+=1,i.tag=tb.decode(e,t),t+=tb.decode.bytes,i.value=to(e,t,n+r),i.issuerCritical=!!(i.flags&tR.ISSUER_CRITICAL),tR.decode.bytes=r+2,i},encodingLength:e=>tb.encodingLength(e.tag)+tb.encodingLength(e.value)+2});tR.ISSUER_CRITICAL=128;let tk=tm({encode(e,t,r){t||(t=new Uint8Array(tk.encodingLength(e))),r||(r=0);let n=r;return r+=2,tf(t,e.preference||0,r),r+=2,ty.encode(e.exchange,t,r),r+=ty.encode.bytes,tf(t,r-n-2,n),tk.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.preference=td(e,t),t+=2,n.exchange=ty.decode(e,t),t+=ty.decode.bytes,tk.decode.bytes=t-r,n},encodingLength:e=>4+ty.encodingLength(e.exchange)}),tP=tm({encode:(e,t,r)=>(t||(t=new Uint8Array(tP.encodingLength(e))),r||(r=0),tf(t,4,r),r+=2,e5.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,e5.decode(e,t)),bytes:6}),tD=tm({encode:(e,t,r)=>(t||(t=new Uint8Array(tD.encodingLength(e))),r||(r=0),tf(t,16,r),r+=2,e8.encode(e,t,r),tD.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;let r=e8.decode(e,t);return tD.decode.bytes=18,r},bytes:18}),tB=e=>new Uint8Array(e),tN=tm({encode(e,t,r){t||(t=new Uint8Array(tN.encodingLength(e))),r||(r=0);let n=r,i=tn(e.code);if(tf(t,i,r),r+=2,e.data)tf(t,e.data.length,r),r+=2,tg(e.data,t,r),r+=e.data.length;else switch(i){case 8:{let n=e.sourcePrefixLength||0,i=e.family||(e9(e.ip)===e5.size?1:2),s=function(e,t,r){r=~~r;let n=e9(e);return("function"==typeof t&&(t=t(r+n)),n===e5.size)?e5.encode(e,t,r):e8.encode(e,t,r)}(e.ip,tB),o=Math.ceil(n/8);tf(t,o+4,r),r+=2,tf(t,i,r),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,tg(s,t,r,0,o),r+=o}break;case 11:e.timeout?(tf(t,2,r),r+=2,tf(t,e.timeout,r)):tf(t,0,r),r+=2;break;case 12:{let n=e.length||0;tf(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{let n=2*e.tags.length;for(let i of(tf(t,n,r),r+=2,e.tags))tf(t,i,r),r+=2}break;default:throw Error(`Unknown roption code: ${e.code}`)}return tN.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r={};r.code=td(e,t),r.type=function(e){switch(e){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return e<0?null:`OPTION_${e}`}(r.code);let n=td(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=td(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{let i=new Uint8Array(1===r.family?4:16);tg(e,i,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===e5.size)return e5.decode(e,t,r);if(r===e8.size)return e8.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${e5.size} for v4 or ${e8.size} for v6.`)}(i)}break;case 11:n>0&&(r.timeout=td(e,t),t+=2);break;case 14:r.tags=[];for(let i=0;i0;)n[s++]=tN.decode(e,t),t+=tN.decode.bytes,i-=tN.decode.bytes;return tL.decode.bytes=t-r,n},encodingLength:e=>2+tX(e||[],tN)}),tx=tm({encode(e,t,r){t||(t=new Uint8Array(tx.encodingLength(e))),r||(r=0);let n=r,i=e.key;if(!ta(i))throw Error("Key must be a Buffer");return r+=2,tf(t,e.flags,r),t[r+=2]=tx.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,r+=1,tg(i,t,r,0,i.length),r+=i.length,tx.encode.bytes=r-n,tf(t,tx.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=td(e,t);if(t+=2,n.flags=td(e,t),e[t+=2]!==tx.PROTOCOL_DNSSEC)throw Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+i+2),t+=n.key.length,tx.decode.bytes=t-r,n},encodingLength:e=>6+tl(e.key)});tx.PROTOCOL_DNSSEC=3,tx.ZONE_KEY=128,tx.SECURE_ENTRYPOINT=32768;let tO=tm({encode(e,t,r){t||(t=new Uint8Array(tO.encodingLength(e))),r||(r=0);let n=r,i=e.signature;if(!ta(i))throw Error("Signature must be a Buffer");return r+=2,tf(t,te(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,tp(t,e.originalTTL,r),r+=4,tp(t,e.expiration,r),r+=4,tp(t,e.inception,r),r+=4,tf(t,e.keyTag,r),r+=2,ty.encode(e.signersName,t,r),r+=ty.encode.bytes,tg(i,t,r,0,i.length),r+=i.length,tO.encode.bytes=r-n,tf(t,tO.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=td(e,t);return t+=2,n.typeCovered=e7(td(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=th(e,t),t+=4,n.expiration=th(e,t),t+=4,n.inception=th(e,t),t+=4,n.keyTag=td(e,t),t+=2,n.signersName=ty.decode(e,t),t+=ty.decode.bytes,n.signature=e.slice(t,r+i+2),t+=n.signature.length,tO.decode.bytes=t-r,n},encodingLength:e=>20+ty.encodingLength(e.signersName)+tl(e.signature)}),tM=tm({encode(e,t,r){t||(t=new Uint8Array(tM.encodingLength(e))),r||(r=0);let n=r;return r+=2,ty.encode(e.mbox||".",t,r),r+=ty.encode.bytes,ty.encode(e.txt||".",t,r),r+=ty.encode.bytes,tM.encode.bytes=r-n,tf(t,tM.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.mbox=ty.decode(e,t)||".",t+=ty.decode.bytes,n.txt=ty.decode(e,t)||".",t+=ty.decode.bytes,tM.decode.bytes=t-r,n},encodingLength:e=>2+ty.encodingLength(e.mbox||".")+ty.encodingLength(e.txt||".")}),tU=tm({encode(e,t,r){t||(t=new Uint8Array(tU.encodingLength(e))),r||(r=0);let n=r,i=[];for(let t=0;t>8]&&(i[r>>8]=[]),i[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e2+ty.encodingLength(e.nextDomain)+tU.encodingLength(e.rrtypes)}),tK=tm({encode(e,t,r){t||(t=new Uint8Array(tK.encodingLength(e))),r||(r=0);let n=r,i=e.salt;if(!ta(i))throw Error("salt must be a Buffer");let s=e.nextDomain;if(!ta(s))throw Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,tf(t,e.iterations,r),t[r+=2]=i.length,r+=1,tg(i,t,r,0,i.length),t[r+=i.length]=s.length,r+=1,tg(s,t,r,0,s.length),r+=s.length,tU.encode(e.rrtypes,t,r),r+=tU.encode.bytes,tK.encode.bytes=r-n,tf(t,tK.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=td(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=td(e,t);let s=e[t+=2];t+=1,n.salt=e.slice(t,t+s);let o=e[t+=s];return t+=1,n.nextDomain=e.slice(t,t+o),t+=o,n.rrtypes=tU.decode(e,t,i-(t-r)),t+=tU.decode.bytes,tK.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+tU.encodingLength(e.rrtypes)}),tV=tm({encode(e,t,r){t||(t=new Uint8Array(tV.encodingLength(e))),r||(r=0);let n=r,i=e.digest;if(!ta(i))throw Error("Digest must be a Buffer");return r+=2,tf(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,r+=1,tg(i,t,r,0,i.length),r+=i.length,tV.encode.bytes=r-n,tf(t,tV.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=td(e,t);return t+=2,n.keyTag=td(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+i+2),t+=n.digest.length,tV.decode.bytes=t-r,n},encodingLength:e=>6+tl(e.digest)});function tH(e){switch(e.toUpperCase()){case"A":return tP;case"PTR":case"CNAME":case"DNAME":return tT;case"TXT":return tA;case"NULL":return tI;case"AAAA":return tD;case"SRV":return tC;case"HINFO":return t_;case"CAA":return tR;case"NS":return tE;case"SOA":return tS;case"MX":return tk;case"OPT":return tL;case"DNSKEY":return tx;case"RRSIG":return tO;case"RP":return tM;case"NSEC":return tF;case"NSEC3":return tK;case"DS":return tV}return tw}let t$=tm({encode(e,t,r){t||(t=new Uint8Array(t$.encodingLength(e))),r||(r=0);let n=r;if(ty.encode(e.name,t,r),r+=ty.encode.bytes,tf(t,te(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw Error("OPT name must be root.");tf(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,tf(t,e.flags||0,r+6),r+=8,tL.encode(e.options||[],t,r),r+=tL.encode.bytes}else{let n=tr(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),tf(t,n,r+2),tp(t,e.ttl||0,r+4),r+=8;let i=tH(e.type);i.encode(e.data,t,r),r+=i.encode.bytes}return t$.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r={},n=t;if(r.name=ty.decode(e,t),t+=ty.decode.bytes,r.type=e7(td(e,t)),"OPT"===r.type)r.udpPayloadSize=td(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=td(e,t+6),r.flag_do=(r.flags>>15&1)==1,r.options=tL.decode(e,t+8),t+=8+tL.decode.bytes;else{let n=td(e,t+2);r.ttl=th(e,t+4),r.class=tt(-32769&n),r.flush=!!(32768&n);let i=tH(r.type);r.data=i.decode(e,t+8),t+=8+i.decode.bytes}return t$.decode.bytes=t-n,r},encodingLength(e){let t=null!==e.data&&void 0!==e.data?e.data:e.options;return ty.encodingLength(e.name)+8+tH(e.type).encodingLength(t)}}),tq=tm({encode(e,t,r){t||(t=new Uint8Array(tq.encodingLength(e))),r||(r=0);let n=r;return ty.encode(e.name,t,r),r+=ty.encode.bytes,tf(t,te(e.type),r),r+=2,tf(t,tr(void 0===e.class?"IN":e.class),r),r+=2,tq.encode.bytes=r-n,e},decode(e,t){t||(t=0);let r=t,n={};return n.name=ty.decode(e,t),t+=ty.decode.bytes,n.type=e7(td(e,t)),t+=2,n.class=tt(td(e,t)),t+=2,32768&n.class&&(n.class&=-32769),tq.decode.bytes=t-r,n},encodingLength:e=>ty.encodingLength(e.name)+4}),tz={encode:function(e,t,r){let n=!t;n&&(t=new Uint8Array(tJ(e))),r||(r=0);let i=r;return(e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),tv.encode(e,t,r),r+=tv.encode.bytes,r=tZ(e.questions,tq,t,r),r=tZ(e.answers,t$,t,r),r=tZ(e.authorities,t$,t,r),r=tZ(e.additionals,t$,t,r),tz.encode.bytes=r-i,n&&tY.bytes!==t.length)?t.slice(0,tY.bytes):t},decode:function(e,t){t||(t=0);let r=t,n=tv.decode(e,t);return t+=tv.decode.bytes,t=t0(n.questions,tq,e,t),t=t0(n.answers,t$,e,t),t=t0(n.authorities,t$,e,t),t=t0(n.additionals,t$,e,t),tz.decode.bytes=t-r,n},encodingLength:function(e){return tv.encodingLength(e)+tX(e.questions||[],tq)+tX(e.answers||[],t$)+tX(e.authorities||[],t$)+tX(e.additionals||[],t$)}};function tj(e,t){if(e.questions)throw Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}tz.encode.bytes=0,tz.decode.bytes=0;let tG={encode:function(e,t,r){return t=tz.encode(tj(e,"query"),t,r),tG.encode.bytes=tz.encode.bytes,t},decode:function(e,t){let r=tz.decode(e,t);return tG.decode.bytes=tz.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return tz.encodingLength(tj(e,"query"))}};tG.encode.bytes=0,tG.decode.bytes=0;let tW={encode:function(e,t,r){return t=tz.encode(tj(e,"response"),t,r),tW.encode.bytes=tz.encode.bytes,t},decode:function(e,t){let r=tz.decode(e,t);return tW.decode.bytes=tz.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return tz.encodingLength(tj(e,"response"))}};tW.encode.bytes=0,tW.decode.bytes=0;let tY=tz.encode,tQ=tz.decode,tJ=tz.encodingLength;function tX(e,t){let r=0;for(let n=0;n255)throw Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==i[r])throw Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);i[r]=e,s[e]=r}let o=r.charCodeAt(0),a={name:e,encodingLength(e){let t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===o?e.charCodeAt(t-2)===o?r-2:r-1:r},encode(e,t,r){null==t&&(t=new Uint8Array(a.encodingLength(e))),null==r&&(r=0);let n=e.length;e.charCodeAt(n-1)===o&&(e.charCodeAt(n-2)===o?n-=2:n-=1);let s=n%4,l=n-s,c=r,u=0;for(;u>16,t[c++]=r>>8,t[c++]=r,u+=4}if(3===s){let r=i[e.charCodeAt(u)]<<10|i[e.charCodeAt(u+1)]<<4|i[e.charCodeAt(u+2)]>>2;t[c++]=r>>8,t[c++]=r}else 2===s&&(t[c++]=i[e.charCodeAt(u)]<<2|i[e.charCodeAt(u+1)]>>4);return a.encode.bytes=c-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);let i=r-t,l=i%3,c=t+i-l,u=[];for(let r=t;r>18&63],s[t>>12&63],s[t>>6&63],s[63&t])}if(2===l){let t=(e[r-2]<<8)+e[r-1];u.push(s[t>>10],s[t>>4&63],s[t<<2&63]),1===n&&u.push(o)}else if(1===l){let t=e[r-1];u.push(s[t>>2],s[t<<4&63]),1===n&&u.push(o,o)}return a.decode.bytes=i,String.fromCharCode.apply(String,u)}};return a}t1("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);let t2=t1("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2),t3="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;t3||(t3=class extends Error{constructor(e="Request aborted."){super(e)}}),t3.prototype.name="AbortError",t3.prototype.code="ABORT_ERR";let t4="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class t6 extends Error{constructor(e,t,r){super("status="+t+" while requesting "+e+" ["+r+"]"),this.uri=e,this.status=t,this.method=r}toJSON(){return{code:this.code,uri:this.uri,status:this.status,method:this.method,endpoint:this.endpoint}}}t6.prototype.name="HTTPStatusError",t6.prototype.code="HTTP_STATUS";class t5 extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:function(e){if("string"==typeof e)return{message:e};try{let t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}let t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}(this.cause)}}}t5.prototype.name="ResponseError",t5.prototype.code="RESPONSE_ERR";class t8 extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}t8.prototype.name="TimeoutError",t8.prototype.code="ETIMEOUT";let t9=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,t7=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i,re=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,rt=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/ig,rr=/\[(((pk|name)=([^\]]+)))\]/ig;function rn(e,t){t.lastIndex=0;let r={};for(;;){let n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class ri extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${rs.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}ri.prototype.name="InvalidProtocolError",ri.prototype.code="EPROTOCOL";let rs=["http:","https:","udp4:","udp6:"];class ro{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;let r="string"==typeof e.port?e.port=parseInt(e.port,10):e.port;if(null==r)this.port=t?"https:"===this.protocol?443:80:e.pk?443:53;else if("number"==typeof r||isNaN(r))this.port=r;else throw Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`)}toJSON(){return this.toString()}}class ra extends ro{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){let e=this.port!==(this.pk?443:53)?`:${this.port}`:"",t=this.pk?` [pk=${this.pk}]`:"",r=this.name?` [name=${this.name}]`:"";return`udp://${this.ipv4||`[${this.ipv6}]`}${e}${t}${r}`}}class rl extends ra{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class rc extends ra{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function ru(e){return t7.test(e)&&!t9.test(e)?`[${e}]`:e}class rh extends ro{constructor(e){if(super(Object.assign({protocol:"https:"},e),!0),!e.host&&(e.ipv4&&(e.host=e.ipv4),e.ipv6&&(e.host=`[${e.ipv6}]`)),!e.host||"string"!=typeof e.host)throw Error(`Invalid Endpoint: host "${e.path}" needs to be set: ${JSON.stringify(e)}`);if(this.host=e.host,this.path=e.path||"/dns-query",this.method=/^post$/i.test(e.method)?"POST":"GET",this.ipv4=e.ipv4,this.ipv6=e.ipv6,!this.ipv6){let e=t7.exec(this.host);e&&(this.ipv6=e[1])}!this.ipv4&&t9.test(this.host)&&(this.ipv4=this.host);let t=`${this.protocol}//${ru(this.host)}:${this.port}${this.path}`;try{this.url=new t4(t)}catch(e){throw Error(e.message+` [${t}]`)}}toString(){let e="https:"===this.protocol?"":"http://",t=this.port!==("https:"===this.protocol?443:80)?`:${this.port}`:"",r="GET"!==this.method?" [post]":"",n="/dns-query"===this.path?"":this.path,i=this.name?` [name=${this.name}]`:"",s=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",o=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${ru(this.host)}${t}${n}${r}${s}${o}${i}`}}function rd(e){let t;if("string"==typeof e)t=function(e){let t=re.exec(e),r=t[2]||"https:",n=t[3],i=t[5],s=t[6],o=t[7];if("https:"===r||"http:"===r){let e=rn(o,rt);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:i,path:s,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){let t=rn(o,rr),s=/^\[(.*)\]$/.exec(n);if(s&&"udp4:"===r)throw Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!s&&"udp6:"===r)throw Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return s?new rc({protocol:"udp6:",ipv6:s[1],port:i,pk:t.pk,name:t.name}):new rl({protocol:"udp4:",ipv4:n,port:i,pk:t.pk,name:t.name})}throw new ri(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw Error(`Can not convert ${e} to an endpoint`);if(e instanceof ro)return e;t=e}(null===t.protocol||void 0===t.protocol)&&(t.protocol="https:");let r=t.protocol;if("udp4:"===r)return new rl(t);if("udp6:"===r)return new rc(t);if("https:"===r||"http:"===r)return new rh(t);throw new ri(r,JSON.stringify(t))}let rp="application/dns-message";function rf(){}async function rg(e,t,r,n){let i=t?t.localStoragePrefix+t.name:null;if(i)try{let e=JSON.parse(localStorage.getItem(i));if(e&&e.time>t.maxTime)return e}catch(e){}let{data:s}=await rm(e,"GET",null,r,n),o={time:Date.now(),data:JSON.parse(to(s))};if(i)try{localStorage.setItem(i,JSON.stringify(o))}catch(e){o.time=null}return o}function rm(e,t,r,n,i){return new Promise((s,o)=>{let a=new t4(e);"GET"===t&&r&&(a.search="?dns="+t2.decode(r));let l=a.toString(),c=new XMLHttpRequest;c.open(t,l,!0),c.setRequestHeader("Accept",rp),"POST"===t&&c.setRequestHeader("Content-Type",rp),c.responseType="arraybuffer",c.timeout=n,c.ontimeout=function(){u(new t8(n));try{c.abort()}catch(e){}},c.onreadystatechange=function(){if(c.readyState>1&&200!==c.status&&0!==c.status){u(new t6(l,c.status,t));try{c.abort()}catch(e){}}},c.onerror=function(){u(200===c.status?Error("Inexplicable XHR Error"):new t6(l,c.status,t))},c.onload=function(){if(200!==c.status)u(new t6(l,c.status,t));else{let e;if("string"==typeof c.response)e=ts(c.response);else if(c.response instanceof Uint8Array)e=c.response;else if(Array.isArray(c.response)||c.response instanceof ArrayBuffer)e=new Uint8Array(c.response);else throw Error("Unprocessable response "+c.response);u(null,e)}},"POST"===t?c.send(r):c.send(),i&&i.addEventListener("abort",h);let u=function(e,t){u=rf,i&&i.removeEventListener("abort",h),e?s({error:e,response:c}):s({data:t,response:c})};function h(){u(new t3);try{c.abort()}catch(e){}}})}function ry(e){let t=null===e.time||void 0===e.time?Date.now():e.time,r=e.data.map(e=>(e.endpoint=rd(Object.assign({name:e.name},e.endpoint)),e)).filter(e=>e.cors||e.endpoint.cors),n=r.map(e=>e.endpoint);return{data:{resolvers:r,resolverByName:r.reduce((e,t)=>(e[t.name]=t,e),{}),endpoints:n,endpointByName:n.reduce((e,t)=>(e[t.name]=t,e),{})},time:t}}let rb=ry({data:[{name:"adfree.usableprivacy.net",endpoint:{protocol:"https:",host:"adfree.usableprivacy.net"},description:"Public updns DoH service with advertising, tracker and malware filters.\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0},{name:"adguard-dns-doh",endpoint:{protocol:"https:",host:"dns.adguard.com",ipv4:"94.140.15.15"},description:"Remove ads and protect your computer from malware (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-family-doh",endpoint:{protocol:"https:",host:"dns-family.adguard.com",ipv4:"94.140.15.16"},description:"Adguard DNS with safesearch and adult content blocking (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-unfiltered-doh",endpoint:{protocol:"https:",host:"dns-unfiltered.adguard.com",ipv4:"94.140.14.140"},description:"AdGuard public DNS servers without filters (over DoH)",country:"France",location:{lat:48.8582,long:2.3387}},{name:"ahadns-doh-chi",endpoint:{protocol:"https:",host:"doh.chi.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Chicago, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=chi",country:"United States",location:{lat:41.8483,long:-87.6517},filter:!0,cors:!0},{name:"ahadns-doh-in",endpoint:{protocol:"https:",host:"doh.in.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Mumbai, India. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=in",country:"India",location:{lat:19.0748,long:72.8856},filter:!0,cors:!0},{name:"ahadns-doh-la",endpoint:{protocol:"https:",host:"doh.la.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Los Angeles, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=la",country:"United States",location:{lat:34.0549,long:-118.2578},filter:!0,cors:!0},{name:"ahadns-doh-nl",endpoint:{protocol:"https:",host:"doh.nl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Amsterdam, Netherlands. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=nl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"ahadns-doh-ny",endpoint:{protocol:"https:",host:"doh.ny.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in New York. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=ny",country:"United States",location:{lat:40.7308,long:-73.9975},filter:!0,cors:!0},{name:"ahadns-doh-pl",endpoint:{protocol:"https:",host:"doh.pl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Poland. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=pl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"alidns-doh",endpoint:{protocol:"https:",host:"dns.alidns.com",ipv4:"223.5.5.5",cors:!0},description:"A public DNS resolver that supports DoH/DoT in mainland China, provided by Alibaba-Cloud.\nWarning: GFW filtering rules are applied by that resolver.\nHomepage: https://alidns.com/",country:"China",location:{lat:34.7725,long:113.7266},filter:!0,log:!0,cors:!0},{name:"ams-ads-doh-nl",endpoint:{protocol:"https:",host:"dnsnl-noads.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.",country:"Romania",location:{lat:45.9968,long:24.997},filter:!0},{name:"ams-doh-nl",endpoint:{protocol:"https:",host:"dnsnl.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Romania",location:{lat:45.9968,long:24.997}},{name:"att",endpoint:{protocol:"https:",host:"dohtrial.att.net"},description:"AT&T test DoH server.",log:!0},{name:"bcn-ads-doh",endpoint:{protocol:"https:",host:"dnses-noads.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611},filter:!0},{name:"bcn-doh",endpoint:{protocol:"https:",host:"dnses.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611}},{name:"brahma-world",endpoint:{protocol:"https:",host:"dns.brahma.world"},description:"DNS-over-HTTPS server. Non Logging, filters ads, trackers and malware. DNSSEC ready, QNAME Minimization, No EDNS Client-Subnet.\nHosted in Stockholm, Sweden. (https://dns.brahma.world)",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"cisco-doh",endpoint:{protocol:"https:",host:"doh.opendns.com",ipv4:"146.112.41.2"},description:"Remove your DNS blind spot (DoH protocol)\nWarning: modifies your queries to include a copy of your network\naddress when forwarding them to a selection of companies and organizations.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0,log:!0},{name:"cloudflare",endpoint:{protocol:"https:",host:"dns.cloudflare.com",ipv4:"1.0.0.1",cors:!0},description:"Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1",country:"Australia",location:{lat:-33.494,long:143.2104},cors:!0},{name:"cloudflare-family",endpoint:{protocol:"https:",host:"family.cloudflare-dns.com",ipv4:"1.0.0.3",cors:!0},description:"Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"cloudflare-ipv6",endpoint:{protocol:"https:",host:"1dot1dot1dot1.cloudflare-dns.com",cors:!0},description:"Cloudflare DNS over IPv6 (anycast)",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"cloudflare-security",endpoint:{protocol:"https:",host:"security.cloudflare-dns.com",ipv4:"1.0.0.2",cors:!0},description:"Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"controld-block-malware",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p1"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p2"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad-social",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p3"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking and Social Networks domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-family-friendly",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/family"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking, Adult Content and Drugs domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-uncensored",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/uncensored"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS unblocks censored domains from various countries.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"controld-unfiltered",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p0"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis is a Unfiltered DNS, no DNS record blocking or manipulation here, if you want to block Malware, Ads & Tracking or Social Network domains, use the other ControlD DNS configs.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"dns.digitale-gesellschaft.ch",endpoint:{protocol:"https:",host:"dns.digitale-gesellschaft.ch"},description:"Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\nHosted in Zurich, Switzerland.\nNon-logging, non-filtering, supports DNSSEC.",country:"Switzerland",location:{lat:47.1449,long:8.1551}},{name:"dns.ryan-palmer",endpoint:{protocol:"https:",host:"dns1.ryan-palmer.com"},description:"Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.",country:"United Kingdom",location:{lat:51.5164,long:-.093}},{name:"dns.sb",endpoint:{protocol:"https:",host:"doh.sb",ipv4:"185.222.222.222",cors:!0},description:"DNSSEC-enabled DoH server by https://xtom.com/\nhttps://dns.sb/doh/",country:"Unknown",location:{lat:47,long:8},cors:!0},{name:"dns.therifleman.name",endpoint:{protocol:"https:",host:"dns.therifleman.name"},description:"DNS-over-HTTPS DNS forwarder from Mumbai, India. Blocks web and Android trackers and ads.\nIP addresses are not logged, but queries are logged for 24 hours for debugging.\nReport issues, send suggestions @ joker349 at protonmail.com.\nAlso supports DoT (for android) @ dns.therifleman.name and plain DNS @ 172.104.206.174",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"dnsforfamily-doh",endpoint:{protocol:"https:",host:"dns-doh.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC). Block adult websites, gambling websites, malwares and advertisements.\nIt also enforces safe search in: Google, YouTube, Bing, DuckDuckGo and Yandex.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforfamily-doh-no-safe-search",endpoint:{protocol:"https:",host:"dns-doh-no-safe-search.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC) Block adult websites, gambling websites, malwares and advertisements.\nUnlike other dnsforfamily servers, this one does not enforces safe search. So Google, YouTube, Bing, DuckDuckGo and Yandex are completely accessible without any restriction.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nWarning: This server is incompatible with anonymization.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforge.de",endpoint:{protocol:"https:",host:"dnsforge.de",cors:!0},description:"Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.",country:"Germany",location:{lat:52.2998,long:9.447},filter:!0,cors:!0},{name:"dnshome-doh",endpoint:{protocol:"https:",host:"dns.dnshome.de"},description:"https://www.dnshome.de/ public resolver in Germany"},{name:"dnspod-doh",endpoint:{protocol:"https:",host:"doh.pub",cors:!0},description:"A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en",filter:!0,log:!0,cors:!0},{name:"dnswarden-asia-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adblock"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-adultfilter-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adultfilter"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-uncensor-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/uncensored"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547}},{name:"dnswarden-eu-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.eu.dnswarden.com"},description:"Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Germany",location:{lat:50.1103,long:8.7147},filter:!0},{name:"dnswarden-us-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.us.dnswarden.com"},description:"Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"United States",location:{lat:32.7889,long:-96.8021},filter:!0},{name:"doh-ch-blahdns",endpoint:{protocol:"https:",host:"doh-ch.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"doh-cleanbrowsing-adult",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/adult-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It does\nnot block proxy or VPNs, nor mixed-content sites. Sites like Reddit\nare allowed. Google and Bing are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-family",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/family-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It also\nblocks proxy and VPN domains that are used to bypass the filters.\nMixed content sites (like Reddit) are also blocked. Google, Bing and\nYoutube are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-security",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/security-filter/",cors:!0},description:"Block access to phishing, malware and malicious domains. It does not block adult content.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-crypto-sx",endpoint:{protocol:"https:",host:"doh.crypto.sx",cors:!0},description:"DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-crypto-sx-ipv6",endpoint:{protocol:"https:",host:"doh-ipv6.crypto.sx",cors:!0},description:"DNS-over-HTTPS server accessible over IPv6. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-de-blahdns",endpoint:{protocol:"https:",host:"doh-de.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0,cors:!0},{name:"doh-fi-blahdns",endpoint:{protocol:"https:",host:"doh-fi.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0,cors:!0},{name:"doh-ibksturm",endpoint:{protocol:"https:",host:"ibksturm.synology.me"},description:"DoH & DoT Server, No Logging, No Filters, DNSSEC\nRunning privately by ibksturm in Thurgau, Switzerland"},{name:"doh-jp-blahdns",endpoint:{protocol:"https:",host:"doh-jp.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/",country:"Japan",location:{lat:35.6882,long:139.7532},filter:!0,cors:!0},{name:"doh.ffmuc.net",endpoint:{protocol:"https:",host:"doh.ffmuc.net"},description:"An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\nhttps://ffmuc.net/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"doh.tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org"},description:"Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"google",endpoint:{protocol:"https:",host:"dns.google",ipv4:"8.8.8.8",cors:!0},description:"Google DNS (anycast)",country:"United States",location:{lat:37.751,long:-97.822},log:!0,cors:!0},{name:"hdns",endpoint:{protocol:"https:",host:"query.hdns.io",cors:!0},description:"HDNS is a public DNS resolver that supports Handshake domains.\nhttps://www.hdns.io",country:"United States",location:{lat:37.7771,long:-122.406},cors:!0},{name:"he",endpoint:{protocol:"https:",host:"ordns.he.net"},description:"Hurricane Electric DoH server (anycast)\nUnknown logging policy.",country:"United States",location:{lat:37.751,long:-97.822},log:!0},{name:"id-gmail-doh",endpoint:{protocol:"https:",host:"doh.tiar.app"},description:"Non-Logging DNS-over-HTTPS server located in Singapore.\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"iij",endpoint:{protocol:"https:",host:"public.dns.iij.jp"},description:"DoH server operated by Internet Initiative Japan in Tokyo.\nhttps://www.iij.ad.jp/",country:"Japan",location:{lat:35.69,long:139.69},log:!0},{name:"iqdns-doh",endpoint:{protocol:"https:",host:"a.passcloud.xyz"},description:'Non-logging DoH service runned by V2EX.com user johnsonwil.\nReturns "no such domain" for anti-Chinese government websites. Supports DNSSEC.\nFor more information: https://www.v2ex.com/t/785666',filter:!0},{name:"jp.tiar.app-doh",endpoint:{protocol:"https:",host:"jp.tiar.app"},description:"Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\nNo ECS, Support DNSSEC",country:"Japan",location:{lat:35.6882,long:139.7532}},{name:"jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org"},description:"DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\nCached via Cloudflare."},{name:"libredns",endpoint:{protocol:"https:",host:"doh.libredns.gr"},description:"DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\nhttps://libredns.gr/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"nextdns",endpoint:{protocol:"https:",host:"anycsast.dns.nextdns.io"},description:"NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nDNSSEC, Anycast, Non-logging, NoFilters\nhttps://www.nextdns.io/",country:"Netherlands",location:{lat:52.3891,long:4.6563}},{name:"nextdns-ultralow",endpoint:{protocol:"https:",host:"dns.nextdns.io",path:"/dnscrypt-proxy"},description:'NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nhttps://www.nextdns.io/\nTo select the server location, the "-ultralow" variant relies on bootstrap servers\ninstead of anycast.'},{name:"njalla-doh",endpoint:{protocol:"https:",host:"dns.njal.la",cors:!0},description:"Non-logging DoH server in Sweden operated by Njalla.\nhttps://dns.njal.la/",country:"Sweden",location:{lat:59.3247,long:18.056},cors:!0},{name:"odoh-cloudflare",endpoint:{protocol:"https:",host:"odoh.cloudflare-dns.com",cors:!0},description:"Cloudflare ODoH server.\nhttps://cloudflare.com",cors:!0},{name:"odoh-crypto-sx",endpoint:{protocol:"https:",host:"odoh.crypto.sx",cors:!0},description:"ODoH target server. Anycast, no logs.\nBackend hosted by Scaleway. Maintained by Frank Denis.",cors:!0},{name:"odoh-id-gmail",endpoint:{protocol:"https:",host:"doh.tiar.app",path:"/odoh"},description:"ODoH target server. Based in Singapore, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"odoh-jp.tiar.app",endpoint:{protocol:"https:",host:"jp.tiar.app",path:"/odoh"},description:"ODoH target server. no logs."},{name:"odoh-jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs."},{name:"odoh-resolver4.dns.openinternet.io",endpoint:{protocol:"https:",host:"resolver4.dns.openinternet.io"},description:"ODoH target server. no logs, no filter, DNSSEC.\nRunning on dedicated hardware colocated at Sonic.net in Santa Rosa, CA in the United States.\nUses Sonic's recusrive DNS servers as upstream resolvers (but is not affiliated with Sonic\nin any way). Provided by https://openinternet.io"},{name:"odoh-tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"publicarray-au2-doh",endpoint:{protocol:"https:",host:"doh-2.seby.io",cors:!0},description:"DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\nMaintained by publicarray - https://dns.seby.io",country:"Australia",location:{lat:-33.8591,long:151.2002},cors:!0},{name:"puredns-doh",endpoint:{protocol:"https:",host:"puredns.org",ipv4:"146.190.6.13",cors:!0},description:"Public uncensored DNS resolver in Singapore - https://puredns.org\n** Only available in Indonesia and Singapore **",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"quad101",endpoint:{protocol:"https:",host:"dns.twnic.tw",cors:!0},description:"DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\nhttps://101.101.101.101/index_en.html",cors:!0},{name:"quad9-doh-ip4-port443-filter-ecs-pri",endpoint:{protocol:"https:",host:"dns11.quad9.net",ipv4:"149.112.112.11"},description:"Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-filter-pri",endpoint:{protocol:"https:",host:"dns.quad9.net",ipv4:"149.112.112.112"},description:"Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-nofilter-ecs-pri",endpoint:{protocol:"https:",host:"dns12.quad9.net",ipv4:"9.9.9.12"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip4-port443-nofilter-pri",endpoint:{protocol:"https:",host:"dns10.quad9.net",ipv4:"149.112.112.10"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip6-port5053-filter-pri",endpoint:{protocol:"https:",host:"dns9.quad9.net"},description:"Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"safesurfer-doh",endpoint:{protocol:"https:",host:"doh.safesurfer.io"},description:"Family safety focused blocklist for over 2 million adult sites, as well as phishing and malware and more.\nFree to use, paid for customizing blocking for more categories+sites and viewing usage at my.safesurfer.io. Logs taken for viewing\nusage, data never sold - https://safesurfer.io",filter:!0,log:!0},{name:"sth-ads-doh-se",endpoint:{protocol:"https:",host:"dnsse-noads.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332},filter:!0},{name:"sth-doh-se",endpoint:{protocol:"https:",host:"dnsse.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332}},{name:"switch",endpoint:{protocol:"https:",host:"dns.switch.ch"},description:"Public DoH service provided by SWITCH in Switzerland\nhttps://www.switch.ch\nProvides protection against malware, but does not block ads.",filter:!0},{name:"uncensoreddns-dk-ipv4",endpoint:{protocol:"https:",host:"unicast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"uncensoreddns-ipv4",endpoint:{protocol:"https:",host:"anycast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"v.dnscrypt.uk-doh-ipv4",endpoint:{protocol:"https:",host:"v.dnscrypt.uk"},description:"DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\nhttps://www.dnscrypt.uk",country:"United Kingdom",location:{lat:51.4964,long:-.1224}}],time:1654187067783}),rv=new t4("https://martinheidegger.github.io/dns-query/resolvers.json");function rw(e){return/^@/.test(e)}class rE{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:rv,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?rg(this.opts.updateURL,this.opts.persist?{name:"resolvers.json",localStoragePrefix:this.opts.localStoragePrefix,maxTime:Date.now()-this.opts.maxAge}:null,this.opts.timeout).then(e=>ry({data:e.data.resolvers,time:e.time})).catch(()=>t||rb):Promise.resolve(rb),this._dataP):this._dataP.then(e=>e.timee.data)}endpoints(e){if(null==e)return this.data().then(e=>e.endpoints);if("doh"===e&&(e=rA),"dns"===e&&(e=rI),"function"==typeof e)return this.data().then(t=>t.endpoints.filter(e));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(rw))try{return Promise.resolve(e.map(rd))}catch(e){return Promise.reject(e)}return this.data().then(t=>e.map(e=>{if(rw(e)){let r=t.endpointByName[e.substring(1)];if(!r)throw Error(`Endpoint ${e} is not known.`);return r}return rd(e)}))}}let rS=new rE;function rA(e){return"https:"===e.protocol||"http:"===e.protocol}function rI(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}let r_=new g.Yd("dns-over-https");class rT{endpoints;retries;static async create(e,t){return new rT(e??await rS.endpoints("doh"),t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{var r,n,i,s;t=(await (r={question:{type:"TXT",name:e}},n={endpoints:this.endpoints,retries:this.retries},(n=Object.assign({retries:5,timeout:3e4},n),r.question)?(null!==(s=i=n.endpoints)&&"object"==typeof s&&"function"==typeof s.then?i:Promise.resolve(i)).then(e=>{if(!Array.isArray(e)||0===e.length)throw Error("No endpoints defined to lookup dns records.");return function e(t,r,n){var i,s,o,a,l;let c=1===t.length?t[0]:t[Math.floor(Math.random()*t.length)%t.length];return(i=n.timeout,(s=n.signal)&&s.aborted?Promise.reject(new t3):"udp4:"===c.protocol||"udp6:"===c.protocol?function(){throw Error('Only "doh" endpoints are supported in the browser')}(c,r,i,s):(o=c.url,a=c.method,l=tY(Object.assign({flags:256},r)),rm(o,a,l,i,s)).then(function(e){let t=e.data,r=e.response,n=e.error;if(void 0===n){if(0===t.length)n=new t5("Empty.");else try{let e=tQ(t);return e.response=r,e}catch(e){n=new t5("Invalid packet (cause="+e.message+")",e)}}throw Object.assign(n,{response:r})})).then(e=>(e.endpoint=c.toString(),e),i=>{if("AbortError"===i.name||0===n.retries)throw i.endpoint=c.toString(),i;return n.retries>0&&(n.retries-=1),e(t,r,n)})}(e.map(rd),function(e){let t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(r),n)}).then(e=>(e.question=e.questions[0],delete e.questions,e)):Promise.reject(Error("To request data you need to specify a .question!")))).answers}catch(e){throw r_.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error(`Could not resolve ${e}`);let o=t.map(e=>e.data),a=[];return o.forEach(e=>{"string"==typeof e?a.push(e):Array.isArray(e)?e.forEach(e=>{"string"==typeof e?a.push(e):a.push((0,v.Md)(e))}):a.push((0,v.Md)(e))}),a}}var rC=r(37017);class rR{static RECORD_PREFIX=eD.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);let r=rR.parseRootValues(e),n=rC.decode.asBytes(t),i=e.split(" sig")[0],s=(0,v.iY)(i);if(!em((0,e0.m)(r.signature,"base64url").slice(0,64),eg(s),new Uint8Array(n)))throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){let t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();let[r,n,i,s]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!i)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!s)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(i),signature:s}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);let t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();let[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}let rk=new g.Yd("discovery:fetch_nodes");async function rP(e,t,r){let n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},i=n.relay+n.store+n.filter+n.lightPush,s={relay:0,store:0,filter:0,lightPush:0},o=0,a=[];for(;!rB(n,s)&&o=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function rN(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function rL(e,t,r){if(rB(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";let n={relay:r.relaythis._search(i,s));return rx.info("retrieved peers: ",o.map(e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map(e=>e.toString())}))),o}constructor(e){this._DNSTreeCache={},this.dns=e}async *getNextPeer(e,t){let r=Math.floor(Math.random()*e.length),{publicKey:n,domain:i}=rR.parseTree(e[r]),s={domain:i,publicKey:n,visits:{}};for await(let e of rD(t,this._errorTolerance,()=>this._search(i,s)))yield e}async _search(e,t){try{let r,n;let i=await this._getTXTRecord(e,t);t.visits[e]=!0;let s=i.startsWith(rR.ROOT_PREFIX)?rR.ROOT_PREFIX:i.startsWith(rR.BRANCH_PREFIX)?rR.BRANCH_PREFIX:i.startsWith(rR.RECORD_PREFIX)?rR.RECORD_PREFIX:"";try{switch(s){case rR.ROOT_PREFIX:return r=rR.parseAndVerifyRoot(i,t.publicKey),await this._search(r,t);case rR.BRANCH_PREFIX:return n=rR.parseBranch(i),r=function(e,t){let r;let n={};for(let[r,i]of e.entries())t.visits[i]&&(n[r]=!0);if(Object.keys(n).length===e.length)throw Error("Unresolvable circular path detected");do r=Math.floor(Math.random()*e.length);while(n[r]);return e[r]}(n,t),await this._search(r,t);case rR.RECORD_PREFIX:return e2.fromString(i);default:return null}}catch(t){return rx.error(`Failed to search DNS tree ${s} at subdomain ${e}: ${t}`),null}}catch(t){return rx.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];let r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");let i=n.join("");return this._DNSTreeCache[e]=i,i}}let rM=new g.Yd("peer-discovery-dns");class rU extends p.L{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;let{enrUrls:r}=t;rM.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){if(rM.info("Starting peer discovery via dns"),this._started=!0,void 0===this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);let{wantedNodeCapabilityCount:t}=this._options,r=await rO.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(let e of this.nextPeer()){if(!this._started)return;let{peerInfo:t,shardInfo:r}=e;if(!t)continue;let n={[y]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}},i=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(y)||(i=!0,await this._components.peerStore.merge(t.id,{tags:n})):(i=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:(0,g.kL)(r)}}})),i&&this.dispatchEvent(new p.A("peer",{detail:t}))}}stop(){this._started=!1}get[f.J](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}function rF(e,t=b){return r=>new rU(r,{enrUrls:e,wantedNodeCapabilityCount:t})}var rK=r(97540),rV=r(75354),rH=r(83431),r$=r(21679),rq=r(37804),rz=r(54164),rj=r(35311);class rG{proto;constructor(e){this.proto=e}static createRequest(e){let{numPeers:t}=e;return new rG({query:{numPeers:t},response:void 0})}encode(){return rj._G.Zj.encode(this.proto)}static decode(e){return new rG(rj._G.Zj.decode(e))}get query(){return this.proto.query}get response(){return this.proto.response}}let rW="/vac/waku/peer-exchange/2.0.0-alpha1",rY=new g.Yd("peer-exchange");class rQ extends rK.p{constructor(e,t){super(rW,e,rY,t)}async query(e){let{numPeers:t}=e,r=rG.createRequest({numPeers:BigInt(t)}),n=await this.peerStore.get(e.peerId);if(!n)return{peerInfos:null,error:rV.K1.NO_PEER_AVAILABLE};let i=await this.getStream(n),s=await (0,rq.z)([r.encode()],r$.c,i,r$.J,async e=>await (0,rH.Z)(e));try{let e=new rz.H;s.forEach(t=>{e.append(t)});let{response:t}=rG.decode(e);if(!t)return rY.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:rV.K1.EMPTY_PAYLOAD};return{peerInfos:await Promise.all(t.peerInfos.map(e=>e.enr).filter(g.$K).map(async e=>({ENR:await e2.fromRLP(e)}))),error:null}}catch(e){return rY.error("Failed to decode push reply",e),{peerInfos:null,error:rV.K1.DECODE_FAILED}}}}let rJ=new g.Yd("peer-exchange-discovery"),rX=rV.$G.PEER_EXCHANGE;class rZ extends p.L{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{let{protocols:t,peerId:r}=e.detail;!t.includes(rW)||this.queryingPeers.has(r.toString())||(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch(e=>rJ.error(`Error querying peer ${e}`)))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new rQ(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(rJ.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(rJ.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[f.J](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{let t=e.toString(),{queryInterval:r=1e4,maxRetries:n=3}=this.options;rJ.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);let i=this.queryAttempts.get(t)??1;if(i>n){this.abortQueriesForPeer(t);return}setTimeout(()=>{this.queryAttempts.set(t,i+1),this.startRecurringQueries(e).catch(e=>{rJ.error(`Error in startRecurringQueries: ${e}`)})},r*i)};async query(e){let{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return rJ.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(let e of r){let{ENR:t}=e;if(!t){rJ.warn("No ENR in peerInfo object, skipping");continue}let{peerId:r,peerInfo:n,shardInfo:i}=t;!r||!n||await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{tags:{[rX]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...i&&{metadata:{shardInfo:(0,g.kL)(i)}}}),rJ.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new p.A("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})))}return{error:null,peerInfos:r}}abortQueriesForPeer(e){rJ.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}}function r0(e){return t=>new rZ(t,e)}var r1=r(90678);let r2=new g.Yd("peer-exchange-discovery"),r3=rV.$G.LOCAL;class r4 extends p.L{components;options;isStarted;peers=[];constructor(e,t){super(),this.components=e,this.options=t,this.isStarted=!1,this.peers=this.getPeersFromLocalStorage()}get[Symbol.toStringTag](){return"@waku/local-peer-cache-discovery"}async start(){if(!this.isStarted){for(let{id:e,address:t}of(r2.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers),this.peers)){let r=await (0,r1.pG)({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[(0,eb.HM)(t)],tags:{[this.options?.tagName??r3]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new p.A("peer",{detail:{id:r,multiaddrs:[(0,eb.HM)(t)]}})))}r2.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(r2.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{let{peerId:t,listenAddrs:r}=e.detail,n=(0,g.Yl)(r),i=this.getPeersFromLocalStorage(),s=i.findIndex(e=>e.id===t.toString());s>=0?i[s].address=n.toString():i.push({id:t.toString(),address:n.toString()}),this.peers=i,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{let e=localStorage.getItem("waku:peers");if(!e)return[];return JSON.parse(e).filter(r6)}catch(e){return r2.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){r2.error("Error saving peers to local storage:",e)}}}function r6(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}function r5(){return(e,t)=>new r4(e,t)}},75354:function(e,t,r){"use strict";var n,i,s,o,a,l,c,u,h,d,p;r.d(t,{eZ:function(){return g},nf:function(){return f},wh:function(){return l},Wq:function(){return a},$Q:function(){return s},K1:function(){return i},Uw:function(){return n},$G:function(){return o}}),(c=n||(n={})).Relay="relay",c.Store="store",c.LightPush="lightpush",c.Filter="filter",(u=i||(i={})).GENERIC_FAIL="Generic error",u.ENCODE_FAILED="Failed to encode",u.DECODE_FAILED="Failed to decode",u.EMPTY_PAYLOAD="Payload is empty",u.SIZE_TOO_BIG="Size is too big",u.TOPIC_NOT_CONFIGURED="Topic not configured",u.NO_PEER_AVAILABLE="No peer available",u.REMOTE_PEER_FAULT="Remote peer fault",u.REMOTE_PEER_REJECTED="Remote peer rejected",u.REQUEST_TIMEOUT="Request timeout",(h=s||(s={})).BACKWARD="backward",h.FORWARD="forward",(d=o||(o={})).BOOTSTRAP="bootstrap",d.PEER_EXCHANGE="peer-exchange",d.LOCAL="local-peer-cache",(p=a||(a={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",p.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",p.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",p.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(l||(l={})).CONNECTION_STATUS="waku:connection";let f="/waku/2/default-waku/proto",g=1},35311:function(e,t,r){"use strict";let n,i,s,o,a,l,c,u,h,d,p,f,g,m,y,b,v,w,E,S,A,I,_,T,C,R,k,P,D,B,N,L,x,O,M,U,F,K;r.d(t,{aF:function(){return eN},kB:function(){return e6},WS:function(){return e5},u:function(){return e4},fi:function(){return e7},_G:function(){return e9},eW:function(){return e8}});var V,H,$,q,z,j,G,W,Y,Q,J,X,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu,eh,ed,ep,ef,eg,em,ey,eb,ev,ew,eE,eS,eA,eI,e_,eT,eC,eR,ek,eP,eD,eB,eN,eL,ex,eO,eM,eU,eF,eK,eV,eH,e$,eq,ez,ej,eG,eW,eY,eQ,eJ,eX,eZ,e0,e1,e2,e3,e4={};r.r(e4),r.d(e4,{H:function(){return eC}});var e6={};r.r(e6),r.d(e6,{ep:function(){return eL},hO:function(){return ex},$p:function(){return eO}});var e5={};r.r(e5),r.d(e5,{xx:function(){return eV}});var e8={};r.r(e8),r.d(e8,{TA:function(){return eW},e9:function(){return eY},BI:function(){return ez}});var e9={};r.r(e9),r.d(e9,{Zj:function(){return e1}});var e7={};r.r(e7),r.d(e7,{v:function(){return e2},_:function(){return e3}});var te=r(47971),tt=r(1514);(V=eT||(eT={})).codec=()=>(null==n&&(n=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),n),V.encode=e=>(0,te.LE)(e,V.codec()),V.decode=(e,t)=>(0,te.C6)(e,V.codec(),t),(H=eC||(eC={})).codec=()=>(null==i&&(i=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eT.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eT.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),i),H.encode=e=>(0,te.LE)(e,H.codec()),H.decode=(e,t)=>(0,te.C6)(e,H.codec(),t),(q=($=eR||(eR={})).ContentFilter||($.ContentFilter={})).codec=()=>(null==o&&(o=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n})),o),q.encode=e=>(0,te.LE)(e,q.codec()),q.decode=(e,t)=>(0,te.C6)(e,q.codec(),t),$.codec=()=>(null==s&&(s=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.subscribe&&!1!==e.subscribe&&(t.uint32(8),t.bool(e.subscribe)),null!=e.topic&&""!==e.topic&&(t.uint32(18),t.string(e.topic)),null!=e.contentFilters)for(let r of e.contentFilters)t.uint32(26),$.ContentFilter.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={subscribe:!1,topic:"",contentFilters:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.subscribe=e.bool();break;case 2:n.topic=e.string();break;case 3:if(r.limits?.contentFilters!=null&&n.contentFilters.length===r.limits.contentFilters)throw new te.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push($.ContentFilter.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;default:e.skipType(7&t)}}return n})),s),$.encode=e=>(0,te.LE)(e,$.codec()),$.decode=(e,t)=>(0,te.C6)(e,$.codec(),t),(z=ek||(ek={})).codec=()=>(null==a&&(a=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(10),eB.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new te.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(eB.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n})),a),z.encode=e=>(0,te.LE)(e,z.codec()),z.decode=(e,t)=>(0,te.C6)(e,z.codec(),t),(j=eP||(eP={})).codec=()=>(null==l&&(l=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),eR.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),ek.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=eR.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=ek.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n})),l),j.encode=e=>(0,te.LE)(e,j.codec()),j.decode=(e,t)=>(0,te.C6)(e,j.codec(),t),(G=eD||(eD={})).codec=()=>(null==c&&(c=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),c),G.encode=e=>(0,te.LE)(e,G.codec()),G.decode=(e,t)=>(0,te.C6)(e,G.codec(),t),(W=eB||(eB={})).codec=()=>(null==u&&(u=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eD.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eD.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),u),W.encode=e=>(0,te.LE)(e,W.codec()),W.decode=(e,t)=>(0,te.C6)(e,W.codec(),t),(Y=eN||(eN={})).codec=()=>(null==h&&(h=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n})),h),Y.encode=e=>(0,te.LE)(e,Y.codec()),Y.decode=(e,t)=>(0,te.C6)(e,Y.codec(),t),(J=d=(Q=eL||(eL={})).FilterSubscribeType||(Q.FilterSubscribeType={})).SUBSCRIBER_PING="SUBSCRIBER_PING",J.SUBSCRIBE="SUBSCRIBE",J.UNSUBSCRIBE="UNSUBSCRIBE",J.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL",(X=p||(p={}))[X.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",X[X.SUBSCRIBE=1]="SUBSCRIBE",X[X.UNSUBSCRIBE=2]="UNSUBSCRIBE",X[X.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL",(d=Q.FilterSubscribeType||(Q.FilterSubscribeType={})).codec=()=>(0,te.Ji)(p),Q.codec=()=>(null==f&&(f=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.filterSubscribeType&&0!==p[e.filterSubscribeType]&&(t.uint32(16),Q.FilterSubscribeType.codec().encode(e.filterSubscribeType,t)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(let r of e.contentTopics)t.uint32(90),t.string(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:"",filterSubscribeType:d.SUBSCRIBER_PING,contentTopics:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.filterSubscribeType=Q.FilterSubscribeType.codec().decode(e);break;case 10:n.pubsubTopic=e.string();break;case 11:if(r.limits?.contentTopics!=null&&n.contentTopics.length===r.limits.contentTopics)throw new te.sv('decode error - map field "contentTopics" had too many elements',"ERR_MAX_LENGTH");n.contentTopics.push(e.string());break;default:e.skipType(7&t)}}return n})),f),Q.encode=e=>(0,te.LE)(e,Q.codec()),Q.decode=(e,t)=>(0,te.C6)(e,Q.codec(),t),(Z=ex||(ex={})).codec=()=>(null==g&&(g=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:"",statusCode:0},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;default:e.skipType(7&t)}}return n})),g),Z.encode=e=>(0,te.LE)(e,Z.codec()),Z.decode=(e,t)=>(0,te.C6)(e,Z.codec(),t),(ee=eO||(eO={})).codec=()=>(null==m&&(m=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),eU.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.wakuMessage=eU.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),m),ee.encode=e=>(0,te.LE)(e,ee.codec()),ee.decode=(e,t)=>(0,te.C6)(e,ee.codec(),t),(et=eM||(eM={})).codec=()=>(null==y&&(y=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),y),et.encode=e=>(0,te.LE)(e,et.codec()),et.decode=(e,t)=>(0,te.C6)(e,et.codec(),t),(er=eU||(eU={})).codec=()=>(null==b&&(b=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eM.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eM.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),b),er.encode=e=>(0,te.LE)(e,er.codec()),er.decode=(e,t)=>(0,te.C6)(e,er.codec(),t),(en=eF||(eF={})).codec=()=>(null==v&&(v=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),e$.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={pubsubTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=e$.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),v),en.encode=e=>(0,te.LE)(e,en.codec()),en.decode=(e,t)=>(0,te.C6)(e,en.codec(),t),(ei=eK||(eK={})).codec=()=>(null==w&&(w=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={isSuccess:!1},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n})),w),ei.encode=e=>(0,te.LE)(e,ei.codec()),ei.decode=(e,t)=>(0,te.C6)(e,ei.codec(),t),(es=eV||(eV={})).codec=()=>(null==E&&(E=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),eF.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),eK.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=eF.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=eK.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),E),es.encode=e=>(0,te.LE)(e,es.codec()),es.decode=(e,t)=>(0,te.C6)(e,es.codec(),t),(eo=eH||(eH={})).codec=()=>(null==S&&(S=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),S),eo.encode=e=>(0,te.LE)(e,eo.codec()),eo.decode=(e,t)=>(0,te.C6)(e,eo.codec(),t),(ea=e$||(e$={})).codec=()=>(null==A&&(A=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eH.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eH.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),A),ea.encode=e=>(0,te.LE)(e,ea.codec()),ea.decode=(e,t)=>(0,te.C6)(e,ea.codec(),t),(el=eq||(eq={})).codec=()=>(null==I&&(I=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.digest&&e.digest.byteLength>0&&(t.uint32(10),t.bytes(e.digest)),null!=e.receiverTime&&0n!==e.receiverTime&&(t.uint32(16),t.sint64(e.receiverTime)),null!=e.senderTime&&0n!==e.senderTime&&(t.uint32(24),t.sint64(e.senderTime)),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(34),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={digest:(0,tt.u)(0),receiverTime:0n,senderTime:0n,pubsubTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.digest=e.bytes();break;case 2:n.receiverTime=e.sint64();break;case 3:n.senderTime=e.sint64();break;case 4:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),I),el.encode=e=>(0,te.LE)(e,el.codec()),el.decode=(e,t)=>(0,te.C6)(e,el.codec(),t),(eu=(ec=ez||(ez={})).Direction||(ec.Direction={})).BACKWARD="BACKWARD",eu.FORWARD="FORWARD",(eh=_||(_={}))[eh.BACKWARD=0]="BACKWARD",eh[eh.FORWARD=1]="FORWARD",(ec.Direction||(ec.Direction={})).codec=()=>(0,te.Ji)(_),ec.codec=()=>(null==T&&(T=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pageSize&&(t.uint32(8),t.uint64(e.pageSize)),null!=e.cursor&&(t.uint32(18),eq.codec().encode(e.cursor,t)),null!=e.direction&&(t.uint32(24),ec.Direction.codec().encode(e.direction,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.pageSize=e.uint64();break;case 2:n.cursor=eq.codec().decode(e,e.uint32(),{limits:r.limits?.cursor});break;case 3:n.direction=ec.Direction.codec().decode(e);break;default:e.skipType(7&t)}}return n})),T),ec.encode=e=>(0,te.LE)(e,ec.codec()),ec.decode=(e,t)=>(0,te.C6)(e,ec.codec(),t),(ed=ej||(ej={})).codec=()=>(null==C&&(C=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n})),C),ed.encode=e=>(0,te.LE)(e,ed.codec()),ed.decode=(e,t)=>(0,te.C6)(e,ed.codec(),t),(ep=eG||(eG={})).codec=()=>(null==R&&(R=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),null!=e.contentFilters)for(let r of e.contentFilters)t.uint32(26),ej.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),ez.codec().encode(e.pagingInfo,t)),null!=e.startTime&&(t.uint32(40),t.sint64(e.startTime)),null!=e.endTime&&(t.uint32(48),t.sint64(e.endTime)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentFilters:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 2:n.pubsubTopic=e.string();break;case 3:if(r.limits?.contentFilters!=null&&n.contentFilters.length===r.limits.contentFilters)throw new te.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(ej.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=ez.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 5:n.startTime=e.sint64();break;case 6:n.endTime=e.sint64();break;default:e.skipType(7&t)}}return n})),R),ep.encode=e=>(0,te.LE)(e,ep.codec()),ep.decode=(e,t)=>(0,te.C6)(e,ep.codec(),t),(eg=k=(ef=eW||(eW={})).HistoryError||(ef.HistoryError={})).NONE="NONE",eg.INVALID_CURSOR="INVALID_CURSOR",eg.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",eg.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",(em=P||(P={}))[em.NONE=0]="NONE",em[em.INVALID_CURSOR=1]="INVALID_CURSOR",em[em.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",em[em.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",(k=ef.HistoryError||(ef.HistoryError={})).codec=()=>(0,te.Ji)(P),ef.codec=()=>(null==D&&(D=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(18),eJ.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(26),ez.codec().encode(e.pagingInfo,t)),null!=e.error&&0!==P[e.error]&&(t.uint32(32),ef.HistoryError.codec().encode(e.error,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[],error:k.NONE},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 2:if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new te.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(eJ.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 3:n.pagingInfo=ez.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 4:n.error=ef.HistoryError.codec().decode(e);break;default:e.skipType(7&t)}}return n})),D),ef.encode=e=>(0,te.LE)(e,ef.codec()),ef.decode=(e,t)=>(0,te.C6)(e,ef.codec(),t),(ey=eY||(eY={})).codec=()=>(null==B&&(B=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.query&&(t.uint32(18),eG.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),eW.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.query=eG.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=eW.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),B),ey.encode=e=>(0,te.LE)(e,ey.codec()),ey.decode=(e,t)=>(0,te.C6)(e,ey.codec(),t),(eb=eQ||(eQ={})).codec=()=>(null==N&&(N=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),N),eb.encode=e=>(0,te.LE)(e,eb.codec()),eb.decode=(e,t)=>(0,te.C6)(e,eb.codec(),t),(ev=eJ||(eJ={})).codec=()=>(null==L&&(L=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eQ.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eQ.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),L),ev.encode=e=>(0,te.LE)(e,ev.codec()),ev.decode=(e,t)=>(0,te.C6)(e,ev.codec(),t),(ew=eX||(eX={})).codec=()=>(null==x&&(x=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n})),x),ew.encode=e=>(0,te.LE)(e,ew.codec()),ew.decode=(e,t)=>(0,te.C6)(e,ew.codec(),t),(eE=eZ||(eZ={})).codec=()=>(null==O&&(O=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n})),O),eE.encode=e=>(0,te.LE)(e,eE.codec()),eE.decode=(e,t)=>(0,te.C6)(e,eE.codec(),t),(eS=e0||(e0={})).codec=()=>(null==M&&(M=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(let r of e.peerInfos)t.uint32(10),eX.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={peerInfos:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(r.limits?.peerInfos!=null&&n.peerInfos.length===r.limits.peerInfos)throw new te.sv('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(eX.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n})),M),eS.encode=e=>(0,te.LE)(e,eS.codec()),eS.decode=(e,t)=>(0,te.C6)(e,eS.codec(),t),(eA=e1||(e1={})).codec=()=>(null==U&&(U=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),eZ.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),e0.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.query=eZ.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=e0.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),U),eA.encode=e=>(0,te.LE)(e,eA.codec()),eA.decode=(e,t)=>(0,te.C6)(e,eA.codec(),t),(eI=e2||(e2={})).codec=()=>(null==F&&(F=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(let r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={shards:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(r.limits?.shards!=null&&n.shards.length===r.limits.shards)throw new te.sv('decode error - map field "shards" had too many elements',"ERR_MAX_LENGTH");n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n})),F),eI.encode=e=>(0,te.LE)(e,eI.codec()),eI.decode=(e,t)=>(0,te.C6)(e,eI.codec(),t),(e_=e3||(e3={})).codec=()=>(null==K&&(K=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(let r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={shards:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(r.limits?.shards!=null&&n.shards.length===r.limits.shards)throw new te.sv('decode error - map field "shards" had too many elements',"ERR_MAX_LENGTH");n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n})),K),e_.encode=e=>(0,te.LE)(e,e_.codec()),e_.decode=(e,t)=>(0,te.C6)(e,e_.codec(),t)},92358:function(e,t,r){"use strict";let n,i,s,o,a,l,c,u,h,d,p,f,g,m,y,b,v,w,E,S,A,I,_,T;r.d(t,{Uw:function(){return tC.Uw},Md:function(){return tJ.Md},UF:function(){return td},Mf:function(){return tu},pq:function(){return lH},iY:function(){return tJ.iY},gT:function(){return tz}});var C,R,k,P,D,B,N,L,x,O,M,U,F,K,V,H,$,q,z,j,G,W,Y,Q,J,X,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu,eh,ed,ep,ef,eg,em,ey,eb,ev,ew,eE,eS,eA,eI,e_,eT,eC,eR,ek,eP,eD,eB,eN,eL,ex,eO,eM,eU,eF,eK,eV,eH,e$,eq,ez,ej,eG,eW,eY,eQ,eJ,eX,eZ,e0,e1,e2,e3,e4,e6,e5,e8,e9,e7,te,tt={};r.r(tt),r.d(tt,{Ed25519PrivateKey:function(){return na},Ed25519PublicKey:function(){return no},generateKeyPair:function(){return nu},generateKeyPairFromSeed:function(){return nh},unmarshalEd25519PrivateKey:function(){return nl},unmarshalEd25519PublicKey:function(){return nc}});var tr={};r.r(tr),r.d(tr,{MAX_KEY_SIZE:function(){return nS},RsaPrivateKey:function(){return nI},RsaPublicKey:function(){return nA},fromJwk:function(){return nC},generateKeyPair:function(){return nR},unmarshalRsaPrivateKey:function(){return n_},unmarshalRsaPublicKey:function(){return nT}});var tn={};r.r(tn),r.d(tn,{Secp256k1PrivateKey:function(){return nB},Secp256k1PublicKey:function(){return nD},generateKeyPair:function(){return nx},unmarshalSecp256k1PrivateKey:function(){return nN},unmarshalSecp256k1PublicKey:function(){return nL}});var ti=r(35311),ts=r(33126);let to=new ts.Yd("message:version-0"),ta=BigInt(1e6);class tl{pubsubTopic;proto;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get _rawTimestamp(){return this.proto.timestamp}get timestamp(){try{if(this.proto.timestamp){let e=this.proto.timestamp/ta;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}class tc{contentTopic;ephemeral;pubsubTopic;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.pubsubTopic=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}async toWire(e){return ti.u.H.encode(await this.toProtoObj(e))}async toProtoObj(e){let t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*ta,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){let e=this.metaSetter(r);return{...r,meta:e}}return r}}function tu({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:i}){return new tc(r,n,(0,ts.IY)(r,e??t),i)}class th{pubsubTopic;contentTopic;constructor(e,t){if(this.pubsubTopic=e,this.contentTopic=t,!t||""===t)throw Error("Content topic must be specified")}fromWireToProtoObj(e){let t=ti.u.H.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(to.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new tl(e,t)}}function td(e,t){return new th((0,ts.IY)(e,t),e)}var tp=r(83431),tf=r(21679),tg=r(37804),tm=r(97540),ty={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let tb=new Uint8Array(16),tv=[];for(let e=0;e<256;++e)tv.push((e+256).toString(16).slice(1));var tw=function(e,t,r){if(ty.randomUUID&&!t&&!e)return ty.randomUUID();let i=(e=e||{}).random||(e.rng||function(){if(!n&&!(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(tb)})();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return tv[e[t+0]]+tv[e[t+1]]+tv[e[t+2]]+tv[e[t+3]]+"-"+tv[e[t+4]]+tv[e[t+5]]+"-"+tv[e[t+6]]+tv[e[t+7]]+"-"+tv[e[t+8]]+tv[e[t+9]]+"-"+tv[e[t+10]]+tv[e[t+11]]+tv[e[t+12]]+tv[e[t+13]]+tv[e[t+14]]+tv[e[t+15]]}(i)};class tE{proto;constructor(e){this.proto=e}static decode(e){return new tE(ti.kB.$p.decode(e))}encode(){return ti.kB.$p.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class tS{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new tS({requestId:tw(),filterSubscribeType:ti.kB.ep.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new tS({requestId:tw(),filterSubscribeType:ti.kB.ep.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new tS({requestId:tw(),filterSubscribeType:ti.kB.ep.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new tS({requestId:tw(),filterSubscribeType:ti.kB.ep.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){return new tS(ti.kB.ep.decode(e))}encode(){return ti.kB.ep.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class tA{proto;constructor(e){this.proto=e}static decode(e){return new tA(ti.kB.hO.decode(e))}encode(){return ti.kB.hO.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}let tI=new ts.Yd("filter:v2"),t_="/vac/waku/filter-push/2.0.0-beta1";class tT extends tm.p{handleIncomingMessage;constructor(e,t,r){super("/vac/waku/filter-subscribe/2.0.0-beta1",t.components,tI,r.pubsubTopics,r),this.handleIncomingMessage=e,t.handle(t_,this.onRequest.bind(this)).catch(e=>{tI.error("Failed to register ",t_,e)})}onRequest(e){let{connection:t,stream:r}=e,{remotePeer:n}=t;tI.info(`Received message from ${n.toString()}`);try{(0,tg.z)(r,tf.J,async e=>{for await(let t of e){let{pubsubTopic:e,wakuMessage:r}=tE.decode(t.slice());if(!r){tI.error("Received empty message");return}if(!e){tI.error("Pubsub topic missing from push message");return}await this.handleIncomingMessage(e,r)}}).then(()=>{tI.info("Receiving pipe closed.")},e=>{tI.error("Error with receiving pipe",e)})}catch(e){tI.error("Error decoding message",e)}}async subscribe(e,t,r){let n=await this.getStream(t),i=tS.createSubscribeRequest(e,r),s=await (0,tg.z)([i.encode()],tf.c,n,tf.J,async e=>await (0,tp.Z)(e));if(!s||!s.length)throw Error(`No response received for request ${i.requestId}: ${s}`);let{statusCode:o,requestId:a,statusDesc:l}=tA.decode(s[0].slice());if(o<200||o>=300)throw Error(`Filter subscribe request ${a} failed with status code ${o}: ${l}`)}async unsubscribe(e,t,r){let n=await this.getStream(t),i=tS.createUnsubscribeRequest(e,r);await (0,tg.z)([i.encode()],tf.c,n.sink)}async unsubscribeAll(e,t){let r=await this.getStream(t),n=tS.createUnsubscribeAllRequest(e),i=await (0,tg.z)([n.encode()],tf.c,r,tf.J,async e=>await (0,tp.Z)(e));if(!i||!i.length)throw Error(`No response received for request ${n.requestId}: ${i}`);let{statusCode:s,requestId:o,statusDesc:a}=tA.decode(i[0].slice());if(s<200||s>=300)throw Error(`Filter unsubscribe all request ${o} failed with status code ${s}: ${a}`)}async ping(e){let t=await this.getStream(e),r=tS.createSubscriberPingRequest();try{let n=await (0,tg.z)([r.encode()],tf.c,t,tf.J,async e=>await (0,tp.Z)(e));if(!n||!n.length)throw Error(`No response received for request ${r.requestId}: ${n}`);let{statusCode:i,requestId:s,statusDesc:o}=tA.decode(n[0].slice());if(i<200||i>=300)throw Error(`Filter ping request ${s} failed with status code ${i}: ${o}`);tI.info(`Ping successful for peer ${e.id.toString()}`)}catch(e){throw tI.error("Error pinging: ",e),e}}}var tC=r(75354),tR=r(54164);class tk{proto;constructor(e){this.proto=e}static createRequest(e,t){return new tk({requestId:tw(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){return new tk(ti.WS.xx.decode(e))}encode(){return ti.WS.xx.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}let tP=new ts.Yd("light-push");class tD extends tm.p{constructor(e,t){super("/vac/waku/lightpush/2.0.0-beta1",e.components,tP,t.pubsubTopics,t)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return tP.error("Failed to send waku light push: payload is empty"),{query:null,error:tC.K1.EMPTY_PAYLOAD};if(!await (0,ts.eh)(e,t))return tP.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:tC.K1.SIZE_TOO_BIG};let r=await e.toProtoObj(t);if(!r)return tP.error("Failed to encode to protoMessage, aborting push"),{query:null,error:tC.K1.ENCODE_FAILED};return{query:tk.createRequest(r,e.pubsubTopic),error:null}}catch(e){return tP.error("Failed to prepare push message",e),{query:null,error:tC.K1.GENERIC_FAIL}}}async send(e,t,r){let n,i,s;let{query:o,error:a}=await this.preparePushMessage(e,t);if(a||!o)return{success:null,failure:{error:a,peerId:r.id}};try{n=await this.getStream(r)}catch(e){return tP.error(`Failed to get a stream for remote peer${r.id.toString()}`,e),{success:null,failure:{error:tC.K1.REMOTE_PEER_FAULT,peerId:r.id}}}try{i=await (0,tg.z)([o.encode()],tf.c,n,tf.J,async e=>await (0,tp.Z)(e))}catch(e){return tP.error("Failed to send waku light push request",e),{success:null,failure:{error:tC.K1.GENERIC_FAIL,peerId:r.id}}}let l=new tR.H;i.forEach(e=>{l.append(e)});try{s=tk.decode(l).response}catch(e){return tP.error("Failed to decode push reply",e),{success:null,failure:{error:tC.K1.DECODE_FAILED,peerId:r.id}}}return s?s.isSuccess?{success:r.id,failure:null}:(tP.error("Remote peer rejected the message: ",s.info),{success:null,failure:{error:tC.K1.REMOTE_PEER_REJECTED,peerId:r.id}}):(tP.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:tC.K1.REMOTE_PEER_FAULT,peerId:r.id}})}}let tB={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},tN=BigInt(1e6);(C=e_||(e_={})).BACKWARD="backward",C.FORWARD="forward";class tL{proto;constructor(e){this.proto=e}get query(){return this.proto.query}get response(){return this.proto.response}static createQuery(e){let t,r;let n=e.contentTopics.map(e=>({contentTopic:e})),i=function(e){switch(e){case e_.BACKWARD:return ti.eW.BI.Direction.BACKWARD;case e_.FORWARD:return ti.eW.BI.Direction.FORWARD;default:return ti.eW.BI.Direction.BACKWARD}}(e.pageDirection),s={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:i};return e.startTime&&(t=BigInt(e.startTime.valueOf())*tN),e.endTime&&(r=BigInt(e.endTime.valueOf())*tN),new tL({requestId:tw(),query:{pubsubTopic:e.pubsubTopic,contentFilters:n,pagingInfo:s,startTime:t,endTime:r},response:void 0})}decode(e){return new tL(ti.eW.e9.decode(e))}encode(){return ti.eW.e9.encode(this.proto)}}var tx=ti.eW.TA.HistoryError;let tO=new ts.Yd("store");class tM extends tm.p{constructor(e,t){super("/vac/waku/store/2.0.0-beta4",e.components,tO,t.pubsubTopics,t)}async *queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.cursor;for(;;){e.cursor=n;let i=tL.createQuery(e),s=await this.getStream(r),o=await (0,tg.z)([i.encode()],tf.c,s,tf.J,async e=>await (0,tp.Z)(e)),a=new tR.H;o.forEach(e=>{a.append(e)});let l=i.decode(a);if(!l.response){tO.warn("Stopping pagination due to store `response` field missing");break}let c=l.response;if(c.error&&c.error!==tx.NONE)throw"History response contains an Error: "+c.error;if(!c.messages||!c.messages.length){tO.warn("Stopping pagination due to store `response.messages` field missing or empty");break}tO.error(`${c.messages.length} messages retrieved from store`),yield c.messages.map(r=>{let n=r.contentTopic;if(void 0!==n){let i=t.get(n);if(i)return i.fromProtoObj(e.pubsubTopic,{...tB,...r})}return Promise.resolve(void 0)});let u=c.pagingInfo?.cursor;if(void 0===u){tO.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");break}n=u;let h=c.pagingInfo?.pageSize,d=i.query?.pagingInfo?.pageSize;if(h&&d&&hvoid 0===globalThis.DOMException?new tF(e):new DOMException(e),tV=e=>{let t=void 0===e.reason?tK("This operation was aborted."):e.reason;return t instanceof Error?t:tK(t)};function tH(e,t){let r;let{milliseconds:n,fallback:i,message:s,customTimers:o={setTimeout,clearTimeout}}=t,a=new Promise((a,l)=>{if("number"!=typeof n||1!==Math.sign(n))throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(t.signal){let{signal:e}=t;e.aborted&&l(tV(e)),e.addEventListener("abort",()=>{l(tV(e))})}if(n===Number.POSITIVE_INFINITY){e.then(a,l);return}let c=new tU;r=o.setTimeout.call(void 0,()=>{if(i){try{a(i())}catch(e){l(e)}return}"function"==typeof e.cancel&&e.cancel(),!1===s?a():s instanceof Error?l(s):(c.message=s??`Promise timed out after ${n} milliseconds`,l(c))},n),(async()=>{try{a(await e)}catch(e){l(e)}})()}).finally(()=>{a.clear()});return a.clear=()=>{o.clearTimeout.call(void 0,r),r=void 0},a}let t$=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}},tq=new ts.Yd("wait-for-remote-peer");async function tz(e,t,r){if(t=t??function(e){let t=[];return e.relay&&t.push(tC.Uw.Relay),e.filter&&t.push(tC.Uw.Filter),e.store&&t.push(tC.Uw.Store),e.lightPush&&t.push(tC.Uw.LightPush),t}(e),!e.isStarted())return Promise.reject("Waku node is not started");let n=[];if(t.includes(tC.Uw.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");n.push(tG(e.relay))}if(t.includes(tC.Uw.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");n.push(tj(e.store.protocol,e.libp2p.services.metadata))}if(t.includes(tC.Uw.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");n.push(tj(e.lightPush.protocol,e.libp2p.services.metadata))}if(t.includes(tC.Uw.Filter)){if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted");n.push(tj(e.filter.protocol,e.libp2p.services.metadata))}r?await tY(Promise.all(n),r,"Timed out waiting for a remote peer."):await Promise.all(n)}async function tj(e,t){let r=e.multicodec,n=await e.connectedPeers();if(n.length){if(!t){tq.info(`${r} peer found: `,n[0].id.toString());return}try{await Promise.any(n.map(e=>t.confirmOrAttemptHandshake(e.id)));return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&tq.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),tq.error(`Error waiting for handshake confirmation: ${e}`)}}tq.info(`Waiting for ${r} peer`),await new Promise(n=>{let i=s=>{s.detail?.protocols?.includes(r)&&(t?t.confirmOrAttemptHandshake(s.detail.peerId).then(()=>{e.removeLibp2pEventListener("peer:identify",i),n()}).catch(e=>{"ERR_CONNECTION_BEING_CLOSED"===e.code&&tq.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),tq.error(`Error waiting for handshake confirmation: ${e}`)}):(e.removeLibp2pEventListener("peer:identify",i),n()))};e.addLibp2pEventListener("peer:identify",i)})}async function tG(e){let t=e.getMeshPeers();for(let r of e.pubsubTopics)for(;0==t.length;)await function(e,t,r){"function"==typeof r&&(r={filter:r});let n=function(e,t,r){let n;let i=new Promise((i,s)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r}).count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let o=[t].flat(),a=[],{addListener:l,removeListener:c}=t$(e),u=(...e)=>{let t=r.multiArgs?e:e[0];(!r.filter||r.filter(t))&&(a.push(t),r.count===a.length&&(n(),i(a)))},h=e=>{n(),s(e)};for(let e of(n=()=>{for(let e of o)c(e,u);for(let e of r.rejectionEvents)c(e,h)},o))l(e,u);for(let e of r.rejectionEvents)l(e,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(a)});if(i.cancel=n,"number"==typeof r.timeout){let e=tH(i,{milliseconds:r.timeout});return e.cancel=n,e}return i}(e,t,r={...r,count:1,resolveImmediately:!1}),i=n.then(e=>e[0]);return i.cancel=n.cancel,i}(e.gossipSub,"gossipsub:heartbeat"),t=e.getMeshPeers(r)}let tW=(e,t)=>new Promise((r,n)=>setTimeout(()=>n(t),e));async function tY(e,t,r){await Promise.race([e,tW(t,r)])}var tQ=r(85931),tJ=r(48215);let tX=new ts.Yd("keep-alive");class tZ{pingKeepAliveTimers;relayKeepAliveTimers;options;relay;constructor(e,t){this.pingKeepAliveTimers=new Map,this.relayKeepAliveTimers=new Map,this.options=e,this.relay=t}start(e,t,r){this.stop(e);let{pingKeepAlive:n,relayKeepAlive:i}=this.options,s=e.toString();if(0!==n){let i=setInterval(()=>{(async()=>{let i;try{try{i=await t.ping(e),tX.info(`Ping succeeded (${s})`,i)}catch(e){tX.error(`Ping failed for peer (${s}). + Next ping will be attempted in ${n} seconds. + `);return}try{await r.patch(e,{metadata:{ping:(0,tJ.iY)(i.toString())}})}catch(e){tX.error("Failed to update ping",e)}}catch(e){tX.error(`Ping failed (${s})`,e)}})()},1e3*n);this.pingKeepAliveTimers.set(s,i)}let o=this.relay;if(o&&0!==i){let t=this.scheduleRelayPings(o,i,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){let t=e.toString();this.pingKeepAliveTimers.has(t)&&(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)),this.relayKeepAliveTimers.has(e)&&(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e))}stopAll(){for(let e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(e,t,r){let n=[];for(let i of e.pubsubTopics){if(!e.getMeshPeers(i).includes(r))continue;let s=tu({pubsubTopicShardInfo:(0,ts.Tf)(i),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),o=setInterval(()=>{tX.info("Sending Waku Relay ping message"),e.send(s,{payload:new Uint8Array([1])}).catch(e=>tX.error("Failed to send relay ping",e))},1e3*t);n.push(o)}return n}}let t0=new ts.Yd("connection-manager");class t1 extends tQ.L{configuredPubsubTopics;static instances=new Map;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];online=!1;isConnected(){return this.online}toggleOnline(){this.online||(this.online=!0,this.dispatchEvent(new tQ.A(tC.wh.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new tQ.A(tC.wh.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,i,s){let o=t1.instances.get(e);return o||(o=new t1(t,r,n,i,s),t1.instances.set(e,o)),o}async getPeersByDiscovery(){let e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map(e=>e.remotePeer),r=[],n=[],i=[],s=[],o=[],a=[];for(let t of e){let e=await this.getTagNamesForPeer(t.id);e.includes(tC.$G.BOOTSTRAP)?r.push(t):e.includes(tC.$G.PEER_EXCHANGE)?n.push(t):e.includes(tC.$G.LOCAL)&&i.push(t)}for(let e of t){let t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(tC.$G.BOOTSTRAP)?s.push(t):r.includes(tC.$G.PEER_EXCHANGE)?o.push(t):r.includes(tC.$G.LOCAL)&&a.push(t)}return{DISCOVERED:{[tC.$G.BOOTSTRAP]:r,[tC.$G.PEER_EXCHANGE]:n,[tC.$G.LOCAL]:i},CONNECTED:{[tC.$G.BOOTSTRAP]:s,[tC.$G.PEER_EXCHANGE]:o,[tC.$G.LOCAL]:a}}}constructor(e,t,r,n,i){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...i},this.keepAliveManager=new tZ(t,n),this.run().then(()=>t0.info("Connection Manager is now running")).catch(e=>t0.error("Unexpected error while running service",e)),this.dialPeerStorePeers().catch(e=>t0.error("Unexpected error while dialing peer store peers",e))}async dialPeerStorePeers(){let e=await this.libp2p.peerStore.all(),t=[];for(let r of e)this.libp2p.getConnections().find(e=>e.remotePeer===r.id)||t.push(this.attemptDial(r.id));try{await Promise.all(t)}catch(e){t0.error("Unexpected error while dialing peer store peers",e)}}async run(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener()}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t{e.tags=Array.from(new Set([...e.tags,...r]))}),this.dialAttemptsForPeer.set(e.toString(),-1);break}catch(r){r instanceof AggregateError?t0.error(`Error dialing peer ${e.toString()} - ${r.errors}`):t0.error(`Error dialing peer ${e.toString()} - ${r.message}`),this.dialErrorsForPeer.set(e.toString(),r),t++,this.dialAttemptsForPeer.set(e.toString(),t)}if(this.currentActiveParallelDialCount--,this.processDialQueue(),t===this.options.maxDialAttemptsForPeer)try{let t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?t0.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):t0.warn("No errors array found for AggregateError"):r=t.message,t0.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e)}catch(t){throw Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),t0.info(`Dropped connection with peer ${e.toString()}`)}catch(t){t0.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount{t0.error(e)})}}startPeerDiscoveryListener(){this.libp2p.addEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onEventHandlers["peer:connect"])}startPeerDisconnectionListener(){this.libp2p.addEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"])}async attemptDial(e){if(await this.shouldDialPeer(e)){if(this.currentActiveParallelDialCount>=this.options.maxParallelDials){this.pendingPeerDialQueue.push(e);return}this.dialPeer(e).catch(t=>{t0.error(`Error dialing peer ${e.toString()} : ${t}`)})}}onEventHandlers={"peer:discovery":e=>{(async()=>{let{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){t0.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{t0.info(`Connected to peer ${e.detail.toString()}`);let t=e.detail;this.keepAliveManager.start(t,this.libp2p.services.ping,this.libp2p.peerStore),(await this.getTagNamesForPeer(t)).includes(tC.$G.BOOTSTRAP)?this.libp2p.getConnections().filter(e=>e.tags.includes(tC.$G.BOOTSTRAP)).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new tQ.A(tC.Wq.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new tQ.A(tC.Wq.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.toggleOnline()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.toggleOffline()})()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return t0.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){let t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return t0.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}). + Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(t0.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(t0.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){return!(await this.getTagNamesForPeer(e)).some(e=>e===tC.$G.BOOTSTRAP)||this.libp2p.getConnections().filter(e=>e.tags.find(e=>e===tC.$G.BOOTSTRAP)).lengththis.configuredPubsubTopics.includes(e))}async getPeerShardInfo(e,t){let r=(await t.get(e)).metadata.get("shardInfo");if(r)return(0,ts.Ix)(r)}}r(47651);let t2=new ts.Yd("metadata"),t3="/vac/waku/metadata/1.0.0";class t4 extends tm.p{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(t3,t.components,t2,(0,ts.yf)(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(t3,e=>{this.onRequest(e)})}async onRequest(e){try{let{stream:t,connection:r}=e,n=ti.fi._.encode(this.shardInfo),i=await (0,tg.z)([n],tf.c,t,tf.J,async e=>await (0,tp.Z)(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);if(s)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){t2.error("Error handling metadata request",e)}}async query(e){let t=ti.fi.v.encode(this.shardInfo),r=await this.peerStore.get(e);if(!r)return{shardInfo:null,error:tC.K1.NO_PEER_AVAILABLE};let n=await this.getStream(r),i=await (0,tg.z)([t],tf.c,n,tf.J,async e=>await (0,tp.Z)(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,o),{shardInfo:o,error:null})}async confirmOrAttemptHandshake(e){let t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}decodeMetadataResponse(e){let t=new tR.H;e.forEach(e=>{t.append(e)});let r=ti.fi._.decode(t);return r?{shardInfo:r,error:null}:(t2.error("Error decoding metadata response"),{shardInfo:null,error:tC.K1.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:(0,ts.kL)(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}var t6=r(60117);class t5 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 t8(e,t,r){let n;if(null==t)return e;if(t.aborted)return Promise.reject(new t5(r?.errorMessage,r?.errorCode));let i=new t5(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise((e,r)=>{n=()=>{r(i)},t.addEventListener("abort",n)})])}finally{null!=n&&t.removeEventListener("abort",n)}}class t9{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=(0,t6.Z)(),this.haveNext=(0,t6.Z)()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=(0,t6.Z)(),e}async throw(e){return this.ended=!0,null!=e&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw Error("Cannot push value onto an ended pushable");if(null!=this.nextResult&&(await this.readNext.promise,null!=this.nextResult))throw Error("NeedNext promise resolved but nextResult was not consumed");null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=(0,t6.Z)(),await t8(this.readNext.promise,t?.signal,t)}}class t7 extends Error{code;constructor(e,t){super(e),this.code=t}}class re extends t7{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}}var rt=r(17954);class rr extends Error{code;constructor(e,t){super(e),this.code=t}}function rn(e,t={}){let r=function(e,t){let r=new t9;e.sink(r).catch(async e=>{await r.end(e)}),e.sink=async e=>{for await(let t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());let i=new tR.H;return{read:async(e,t)=>{let r;t?.signal?.throwIfAborted();let s=new Promise((e,n)=>{r=()=>{n(new re("Read aborted"))},t?.signal?.addEventListener("abort",r)});try{if(null==e){let{done:e,value:t}=await Promise.race([n.next(),s]);if(!0===e)return new tR.H;return t}for(;i.byteLength{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(i.byteLength>0){let r=e.source;e.source=async function*(){t?.yieldBytes===!1?yield i:yield*i,yield*r}()}return e}}}(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=rt.P$(t.maxDataLength));let n=t?.lengthDecoder??rt.Jx,i=t?.lengthEncoder??rt.cv;return{read:async e=>{let i=-1,s=new tR.H;for(;;){s.append(await r.read(1,e));try{i=n(s)}catch(e){if(e instanceof RangeError)continue;throw e}if(t?.maxLengthLength!=null&&s.byteLength>t.maxLengthLength)throw new rr("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(i>-1)break}if(t?.maxDataLength!=null&&i>t.maxDataLength)throw new rr("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(i,e)},write:async(e,t)=>{await r.write(new tR.H(i(e.byteLength),e),t)},writeV:async(e,t)=>{let n=new tR.H(...e.flatMap(e=>[i(e.byteLength),e]));await r.write(n,t)},unwrap:()=>r.unwrap()}}function ri(){let e=(0,t6.Z)(),t=!1;return{sink:async r=>{if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){let t=await e.promise;yield*t}()}}var rs=r(1514);let ro=!!globalThis.process?.env?.DUMP_SESSION_KEYS,ra=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));function rl(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}let rc=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw Error("Non little-endian hardware is not supported");function ru(e){if("string"!=typeof e)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function rh(e){if("string"==typeof e)e=ru(e);else if(rl(e))e=e.slice();else throw Error(`expected Uint8Array, got ${typeof e}`);return e}let rd=e=>"[object Object]"===Object.prototype.toString.call(e)&&e.constructor===Object;function rp(e,t){if(!rl(e))throw Error("Uint8Array expected");if("number"==typeof t&&e.length!==t)throw Error(`Uint8Array length ${t} expected`)}function rf(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),l=n?4:0,c=n?0:4;e.setUint32(t+l,o,n),e.setUint32(t+c,a,n)}function rg(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`wrong positive integer: ${e}`)}function rm(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function ry(e,...t){if(!(null!=e&&"object"==typeof e&&(e instanceof Uint8Array||"Uint8Array"===e.constructor.name)))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function rb(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}let rv=(e,t)=>255&e[t++]|(255&e[t++])<<8;class rw{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,rp(e=rh(e),32);let t=rv(e,0),r=rv(e,2),n=rv(e,4),i=rv(e,6),s=rv(e,8),o=rv(e,10),a=rv(e,12),l=rv(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|o<<2)&8191,this.r[7]=(o>>>11|a<<5)&8065,this.r[8]=(a>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=rv(e,16+2*t)}process(e,t,r=!1){let{h:n,r:i}=this,s=i[0],o=i[1],a=i[2],l=i[3],c=i[4],u=i[5],h=i[6],d=i[7],p=i[8],f=i[9],g=rv(e,t+0),m=rv(e,t+2),y=rv(e,t+4),b=rv(e,t+6),v=rv(e,t+8),w=rv(e,t+10),E=rv(e,t+12),S=rv(e,t+14),A=n[0]+(8191&g),I=n[1]+((g>>>13|m<<3)&8191),_=n[2]+((m>>>10|y<<6)&8191),T=n[3]+((y>>>7|b<<9)&8191),C=n[4]+((b>>>4|v<<12)&8191),R=n[5]+(v>>>1&8191),k=n[6]+((v>>>14|w<<2)&8191),P=n[7]+((w>>>11|E<<5)&8191),D=n[8]+((E>>>8|S<<8)&8191),B=n[9]+(S>>>5|(r?0:2048)),N=0,L=0+A*s+5*f*I+5*p*_+5*d*T+5*h*C;N=L>>>13,L&=8191,L+=5*u*R+5*c*k+5*l*P+5*a*D+5*o*B,N+=L>>>13,L&=8191;let x=N+A*o+I*s+5*f*_+5*p*T+5*d*C;N=x>>>13,x&=8191,x+=5*h*R+5*u*k+5*c*P+5*l*D+5*a*B,N+=x>>>13,x&=8191;let O=N+A*a+I*o+_*s+5*f*T+5*p*C;N=O>>>13,O&=8191,O+=5*d*R+5*h*k+5*u*P+5*c*D+5*l*B,N+=O>>>13,O&=8191;let M=N+A*l+I*a+_*o+T*s+5*f*C;N=M>>>13,M&=8191,M+=5*p*R+5*d*k+5*h*P+5*u*D+5*c*B,N+=M>>>13,M&=8191;let U=N+A*c+I*l+_*a+T*o+C*s;N=U>>>13,U&=8191,U+=5*f*R+5*p*k+5*d*P+5*h*D+5*u*B,N+=U>>>13,U&=8191;let F=N+A*u+I*c+_*l+T*a+C*o;N=F>>>13,F&=8191,F+=R*s+5*f*k+5*p*P+5*d*D+5*h*B,N+=F>>>13,F&=8191;let K=N+A*h+I*u+_*c+T*l+C*a;N=K>>>13,K&=8191,K+=R*o+k*s+5*f*P+5*p*D+5*d*B,N+=K>>>13,K&=8191;let V=N+A*d+I*h+_*u+T*c+C*l;N=V>>>13,V&=8191,V+=R*a+k*o+P*s+5*f*D+5*p*B,N+=V>>>13,V&=8191;let H=N+A*p+I*d+_*h+T*u+C*c;N=H>>>13,H&=8191,H+=R*l+k*a+P*o+D*s+5*f*B,N+=H>>>13,H&=8191;let $=N+A*f+I*p+_*d+T*h+C*u;N=$>>>13,$&=8191,$+=R*c+k*l+P*a+D*o+B*s,N+=$>>>13,$&=8191,L=8191&(N=(N=(N<<2)+N|0)+L|0),N>>>=13,x+=N,n[0]=L,n[1]=x,n[2]=O,n[3]=M,n[4]=U,n[5]=F,n[6]=K,n[7]=V,n[8]=H,n[9]=$}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let i=(1^n)-1;for(let e=0;e<10;e++)r[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+t[0];e[0]=65535&s;for(let r=1;r<8;r++)s=(e[r]+t[r]|0)+(s>>>16)|0,e[r]=65535&s}update(e){rb(this);let{buffer:t,blockLen:r}=this,n=(e=rh(e)).length;for(let i=0;i>>0,e[i++]=r[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let rE=function(e){let t=(t,r)=>e(r).update(rh(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(e=>new rw(e)),rS=ru("expand 16-byte k"),rA=ru("expand 32-byte k"),rI=ra(rS),r_=ra(rA);function rT(e,t){return e<>>32-t}function rC(e){return e.byteOffset%4==0}let rR=4294967296-1,rk=new Uint32Array;function rP(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=function(e,t){if(void 0!==t&&("object"!=typeof t||!rd(t)))throw Error("options must be object or undefined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return rg(i),rg(o),rm(s),rm(r),(t,a,l,c,u=0)=>{ry(t),ry(a),ry(l);let h=l.length;if(c||(c=new Uint8Array(h)),ry(c),rg(u),u<0||u>=rR)throw Error("arx: counter overflow");if(c.length=rR)throw Error("arx: counter overflow");let g=Math.min(64,l-f);if(h&&64===g){let e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)p[r=e+t]=d[r]^u[t];f+=64;continue}for(let e=0,t;e0;)d.pop().fill(0);return c}}function rD(e,t,r,n,i,s=20){let o=e[0],a=e[1],l=e[2],c=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=r[0],v=r[1],w=r[2],E=o,S=a,A=l,I=c,_=u,T=h,C=d,R=p,k=f,P=g,D=m,B=y,N=i,L=b,x=v,O=w;for(let e=0;e{e.update(t);let r=t.length%16;r&&e.update(rL.subarray(r))},rO=new Uint8Array(32);function rM(e,t,r,n,i){let s=e(t,r,rO),o=rE.create(s);i&&rx(o,i),rx(o,n);let a=new Uint8Array(16),l=rc(a);rf(l,0,BigInt(i?i.length:0),!0),rf(l,8,BigInt(n.length),!0),o.update(a);let c=o.digest();return s.fill(0),c}let rU=e=>(t,r,n)=>(rp(t,32),rp(r),{encrypt:(i,s)=>{let o=i.length,a=o+16;s?rp(s,a):s=new Uint8Array(a),e(t,r,i,s,1);let l=rM(e,t,r,s.subarray(0,-16),n);return s.set(l,o),s},decrypt:(i,s)=>{let o=i.length,a=o-16;if(o<16)throw Error("encrypted data must be at least 16 bytes");s?rp(s,a):s=new Uint8Array(a);let l=i.subarray(0,-16);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(0,rj.J)(e.subarray()),getHKDF(e,t){var r,n;let i=(r=rj.J,n=e,(0,rV.vp)(r),void 0===n&&(n=new Uint8Array(r.outputLen)),(0,r$.b)(r,(0,rH.O0)(n),(0,rH.O0)(t))),s=function(e,t,r,n=32){if((0,rV.vp)(e),(0,rV.Rx)(n),n>255*e.outputLen)throw Error("Length should be <= 255*HashLen");let i=Math.ceil(n/e.outputLen);void 0===r&&(r=rz);let s=new Uint8Array(i*e.outputLen),o=r$.b.create(e,t),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let t=0;t({publicKey:rK.Sg.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>rK.Sg.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>rF(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>rF(n,t,r).decrypt(e.subarray(),i)},rW=e=>{let t=(0,rs.E)(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};rW.bytes=2;let rY=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};rY.bytes=2;class rQ extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=rQ.code}static code="ERR_UNEXPECTED_PEER"}class rJ extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=rJ.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}r(66163),r(89113);var rX=r(22852),rZ=r(95482),r0=r(60565),r1=r(75360),r2=r(60575),r3=r(30024),r4=r(38856);r(77939),r(51275);var r6=r(83508),r5=r(12528);function r8(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=0===r[0]?r.subarray(1):r,null!=t){if(r.length>t)throw Error("byte array longer than desired length");r=(0,r6.z)([new Uint8Array(t-r.length),r])}return(0,r5.B)(r,"base64url")}function r9(e){var t,r;let n=(t=e,(0,r0.m)(t,"base64urlpad"));return new rZ.jsbn.BigInteger((0,r5.B)(n,"base16"),16)}function r7(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}function ne(e,t){let r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}var nt=r(84018),nr={get(e=globalThis){let t=e.crypto;if(null==t||null==t.subtle)throw Object.assign(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 t}};let nn={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function ni(e,t){let r=function(e){let t=(void 0)??"AES-GCM",r=(void 0)??16,n=(void 0)??12,i=e?.digest??"SHA-256",s=e?.saltLength??16,o=e?.iterations??32767,a=nr.get();async function l(e,l){let c;let u=a.getRandomValues(new Uint8Array(s)),h={name:t,iv:a.getRandomValues(new Uint8Array(n))};if("string"==typeof l&&(l=(0,r0.m)(l)),0===l.length){c=await a.subtle.importKey("jwk",nn,{name:"AES-GCM"},!0,["encrypt"]);try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}catch{c=await a.subtle.importKey("jwk",nn,{name:"AES-GCM"},!0,["encrypt"])}}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}let d=await a.subtle.encrypt(h,c,e);return(0,r6.z)([u,h.iv,new Uint8Array(d)])}async function c(e,l){let c;let u=e.subarray(0,s),h=e.subarray(s,s+n),d=e.subarray(s+n);if("string"==typeof l&&(l=(0,r0.m)(l)),0===l.length)try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}catch{c=await a.subtle.importKey("jwk",nn,{name:"AES-GCM"},!0,["decrypt"])}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}return new Uint8Array(await a.subtle.decrypt({name:t,iv:h},c,d))}return r*=8,{encrypt:l,decrypt:c}}(),n=await r.encrypt(e,t);return nt.base64.encode(n)}var ns=r(47971);(P=eT||(eT={})).RSA="RSA",P.Ed25519="Ed25519",P.Secp256k1="Secp256k1",(D=eC||(eC={}))[D.RSA=0]="RSA",D[D.Ed25519=1]="Ed25519",D[D.Secp256k1=2]="Secp256k1",(eT||(eT={})).codec=()=>(0,ns.Ji)(eC),(B=eR||(eR={})).codec=()=>(null==s&&(s=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eT.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=eT.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),s),B.encode=e=>(0,ns.LE)(e,B.codec()),B.decode=e=>(0,ns.C6)(e,B.codec()),(N=ek||(ek={})).codec=()=>(null==o&&(o=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eT.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=eT.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),o),N.encode=e=>(0,ns.LE)(e,N.codec()),N.decode=e=>(0,ns.C6)(e,N.codec());class no{_key;constructor(e){this._key=nd(e,32)}verify(e,t){var r;return r=this._key,rK.UN.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}marshal(){return this._key}get bytes(){return eR.encode({Type:eT.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,r4.f)(this.bytes,e.bytes)}hash(){let e=r3.sha256.digest(this.bytes);return r7(e)?e.then(({bytes:e})=>e):e.bytes}}class na{_key;_publicKey;constructor(e,t){this._key=nd(e,64),this._publicKey=nd(t,32)}sign(e){return function(e,t){let r=e.subarray(0,32);return rK.UN.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new no(this._publicKey)}marshal(){return this._key}get bytes(){return ek.encode({Type:eT.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,r4.f)(this.bytes,e.bytes)}async hash(){let e;let t=r3.sha256.digest(this.bytes);return r7(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let e=r2.identity.digest(this.public.bytes);return r1.base58btc.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return ni(this.bytes,e);throw new rX.sv(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function nl(e){return e.length>64?new na((e=nd(e,96)).subarray(0,64),e.subarray(64,e.length)):new na((e=nd(e,64)).subarray(0,64),e.subarray(32))}function nc(e){return new no(e=nd(e,32))}async function nu(){let{privateKey:e,publicKey:t}=function(){let e=rK.UN.utils.randomPrivateKey(),t=rK.UN.getPublicKey(e);return{privateKey:ne(e,t),publicKey:t}}();return new na(e,t)}async function nh(e){let{privateKey:t,publicKey:r}=function(e){if(32!==e.length)throw TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=rK.UN.getPublicKey(e);return{privateKey:ne(e,t),publicKey:t}}(e);return new na(t,r)}function nd(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new rX.sv(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}function np(e,t){return t.map(t=>r9(e[t]))}async function nf(e){let t=await nr.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await nb(t);return{privateKey:r[0],publicKey:r[1]}}async function ng(e){let t=[await nr.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await nv(e)],r=await nb({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function nm(e,t){let r=await nr.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await nr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function ny(e,t,r){let n=await nr.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return nr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function nb(e){if(null==e.privateKey||null==e.publicKey)throw new rX.sv("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([nr.get().subtle.exportKey("jwk",e.privateKey),nr.get().subtle.exportKey("jwk",e.publicKey)])}async function nv(e){return nr.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function nw(e,t,r,n){let i=t?rZ.pki.setRsaPublicKey(...np(e,["n","e"])):rZ.pki.setRsaPrivateKey(...np(e,["n","e","d","p","q","dp","dq","qi"])),s=n((0,r5.B)(r instanceof Uint8Array?r:r.subarray(),"ascii"),i);return(0,r0.m)(s,"ascii")}function nE(e){if("RSA"!==e.kty)throw new rX.sv("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new rX.sv("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*(0,r0.m)(e.n,"base64url").length}r(56334),r(87821);let nS=8192;class nA{_key;constructor(e){this._key=e}verify(e,t){return ny(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new rX.sv("JWK was missing components","ERR_INVALID_PARAMETERS");let t=rZ.pki.publicKeyToAsn1({n:r9(e.n),e:r9(e.e)});return(0,r0.m)(rZ.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return eR.encode({Type:eT.RSA,Data:this.marshal()}).subarray()}encrypt(e){return nw(this._key,!0,e,(e,t)=>t.encrypt(e))}equals(e){return(0,r4.f)(this.bytes,e.bytes)}hash(){let e=r3.sha256.digest(this.bytes);return r7(e)?e.then(({bytes:e})=>e):e.bytes}}class nI{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return function(e){if(isNaN(16))throw new rX.sv("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return(0,rH.O6)(16)}(16)}sign(e){return nm(this._key,e)}get public(){if(null==this._publicKey)throw new rX.sv("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new nA(this._publicKey)}decrypt(e){return nw(this._key,!1,e,(e,t)=>t.decrypt(e))}marshal(){return function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new rX.sv("JWK was missing components","ERR_INVALID_PARAMETERS");let t=rZ.pki.privateKeyToAsn1({n:r9(e.n),e:r9(e.e),d:r9(e.d),p:r9(e.p),q:r9(e.q),dP:r9(e.dp),dQ:r9(e.dq),qInv:r9(e.qi)});return(0,r0.m)(rZ.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return ek.encode({Type:eT.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,r4.f)(this.bytes,e.bytes)}hash(){let e=r3.sha256.digest(this.bytes);return r7(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,r5.B)(e,"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t){let t=new rZ.util.ByteBuffer(this.marshal()),r=rZ.asn1.fromDer(t),n=rZ.pki.privateKeyFromAsn1(r);return rZ.pki.encryptRsaPrivateKey(n,e,{algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"})}if("libp2p-key"===t)return ni(this.bytes,e);throw new rX.sv(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function n_(e){let t=function(e){let t=rZ.asn1.fromDer((0,r5.B)(e,"ascii")),r=rZ.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:r8(r.n),e:r8(r.e),d:r8(r.d),p:r8(r.p),q:r8(r.q),dp:r8(r.dP),dq:r8(r.dQ),qi:r8(r.qInv),alg:"RS256"}}(e);if(nE(t)>nS)throw new rX.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await ng(t);return new nI(r.privateKey,r.publicKey)}function nT(e){let t=function(e){let t=rZ.asn1.fromDer((0,r5.B)(e,"ascii")),r=rZ.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:r8(r.n),e:r8(r.e)}}(e);if(nE(t)>nS)throw new rX.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new nA(t)}async function nC(e){if(nE(e)>nS)throw new rX.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ng(e);return new nI(t.privateKey,t.publicKey)}async function nR(e){if(e>nS)throw new rX.sv("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await nf(e);return new nI(t.privateKey,t.publicKey)}var nk=r(14374);function nP(e){try{nk.kA.ProjectivePoint.fromHex(e)}catch(e){throw new rX.sv(String(e),"ERR_INVALID_PUBLIC_KEY")}}class nD{_key;constructor(e){nP(e),this._key=e}verify(e,t){return function(e,t,r){let n=r3.sha256.digest(r instanceof Uint8Array?r:r.subarray());if(r7(n))return n.then(({digest:r})=>nk.kA.verify(t,r,e)).catch(e=>{throw new rX.sv(String(e),"ERR_INVALID_INPUT")});try{return nk.kA.verify(t,n.digest,e)}catch(e){throw new rX.sv(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){var e;return e=this._key,nk.kA.ProjectivePoint.fromHex(e).toRawBytes(!0)}get bytes(){return eR.encode({Type:eT.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,r4.f)(this.bytes,e.bytes)}async hash(){let e;let t=r3.sha256.digest(this.bytes);return r7(t)?{bytes:e}=await t:e=t.bytes,e}}class nB{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return nk.kA.getPublicKey(e,!0)}catch(e){throw new rX.sv(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{nk.kA.getPublicKey(e,!0)}catch(e){throw new rX.sv(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),nP(this._publicKey)}sign(e){return function(e,t){let r=r3.sha256.digest(t instanceof Uint8Array?t:t.subarray());if(r7(r))return r.then(({digest:t})=>nk.kA.sign(t,e).toDERRawBytes()).catch(e=>{throw new rX.sv(String(e),"ERR_INVALID_INPUT")});try{return nk.kA.sign(r.digest,e).toDERRawBytes()}catch(e){throw new rX.sv(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new nD(this._publicKey)}marshal(){return this._key}get bytes(){return ek.encode({Type:eT.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,r4.f)(this.bytes,e.bytes)}hash(){let e=r3.sha256.digest(this.bytes);return r7(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,r5.B)(e,"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return ni(this.bytes,e);throw new rX.sv(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function nN(e){return new nB(e)}function nL(e){return new nD(e)}async function nx(){return new nB(nk.kA.utils.randomPrivateKey())}let nO={rsa:tr,ed25519:tt,secp256k1:tn};function nM(e){let t=Object.keys(nO).join(" / ");return new rX.sv(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}async function nU(e){let t=ek.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case eT.RSA:return nO.rsa.unmarshalRsaPrivateKey(r);case eT.Ed25519:return nO.ed25519.unmarshalEd25519PrivateKey(r);case eT.Secp256k1:return nO.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw nM(t.Type??"RSA")}}var nF=r(65301);async function nK(e,t,r){var n;let i=await nV(e,n$(t));if(null==e.publicKey)throw Error("PublicKey was missing from local PeerId");return n=e.publicKey,eD.encode({identityKey:n,identitySig:i,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function nV(e,t){if(null==e.privateKey)throw Error("PrivateKey was missing from PeerId");return(await nU(e.privateKey)).sign(t)}async function nH(e){return(0,nF.y5)(e.identityKey)}function n$(e){let t=(0,r0.m)("noise-libp2p-static-key:");return e instanceof Uint8Array?(0,r6.z)([t,e],t.length+e.length):(e.prepend(t),e)}async function nq(e,t,r){let n=await (0,nF.y5)(t.identityKey);if(!n.equals(r))throw Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=n$(e);if(null==n.publicKey)throw Error("PublicKey was missing from PeerId");if(null==t.identitySig)throw Error("Signature was missing from message");let s=function(e){let t=eR.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case eT.RSA:return nO.rsa.unmarshalRsaPublicKey(r);case eT.Ed25519:return nO.ed25519.unmarshalEd25519PublicKey(r);case eT.Secp256k1:return nO.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw nM(t.Type??"unknown")}}(n.publicKey);if(!await s.verify(i,t.identitySig))throw Error("Static key doesn't match to peer that signed payload!");return n}function nz(e){return!!(e instanceof Uint8Array||(0,tR.Z)(e))&&32===e.byteLength}(L=eP||(eP={})).codec=()=>(null==a&&(a=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(let r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r})),a),L.encode=e=>(0,ns.LE)(e,L.codec()),L.decode=e=>(0,ns.C6)(e,L.codec()),(x=eD||(eD={})).codec=()=>(null==l&&(l=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),eP.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={identityKey:(0,rs.u)(0),identitySig:(0,rs.u)(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=eP.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r})),l),x.encode=e=>(0,ns.LE)(e,x.codec()),x.decode=e=>(0,ns.C6)(e,x.codec());class nj{n;bytes;view;constructor(e=0){this.n=e,this.bytes=(0,rs.u)(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}}class nG{crypto;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=t}encryptWithAd(e,t,r){let n=this.encrypt(e.k,e.n,t,r);return e.n.increment(),n}decryptWithAd(e,t,r,n){let{plaintext:i,valid:s}=this.decrypt(e.k,e.n,t,r,n);return s&&e.n.increment(),{plaintext:i,valid:s}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return(0,rs.u)(32)}isEmptyKey(e){let t=this.createEmptyKey();return(0,r4.f)(t,e)}encrypt(e,t,r,n){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(n,t.getBytes(),r,e)}encryptAndHash(e,t){let r;return r=this.hasKey(e.cs)?this.encryptWithAd(e.cs,e.h,t):t,this.mixHash(e,r),r}decrypt(e,t,r,n,i){t.assertValue();let s=this.crypto.chaCha20Poly1305Decrypt(n,t.getBytes(),r,e,i);return s?{plaintext:s,valid:!0}:{plaintext:(0,rs.u)(0),valid:!1}}decryptAndHash(e,t){let r;let n=!0;return this.hasKey(e.cs)?{plaintext:r,valid:n}=this.decryptWithAd(e.cs,e.h,t):r=t,this.mixHash(e,t),{plaintext:r,valid:n}}dh(e,t){try{let r=this.crypto.generateX25519SharedKey(e,t);if(32===r.length)return r;return r.subarray(0,32)}catch(e){return this.log.error("error deriving shared key",e),(0,rs.u)(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(new tR.H(e,t))}mixKey(e,t){let[r,n]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(n),e.ck=r}initializeKey(e){return{k:e,n:new nj}}initializeSymmetric(e){let t=(0,r0.m)(e,"utf-8"),r=this.hashProtocolName(t),n=this.createEmptyKey();return{cs:this.initializeKey(n),ck:r,h:r}}hashProtocolName(e){if(!(e.length<=32))return this.getHash(e,(0,rs.u)(0));{let t=(0,rs.u)(32);return t.set(e),t}}split(e){let[t,r]=this.crypto.getHKDF(e.ck,(0,rs.u)(0));return{cs1:this.initializeKey(t),cs2:this.initializeKey(r)}}writeMessageRegular(e,t){let r=this.encryptWithAd(e,(0,rs.u)(0),t);return{ne:this.createEmptyKey(),ns:(0,rs.u)(0),ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,(0,rs.u)(0),t.ciphertext)}}class nW extends nG{initializeInitiator(e,t,r,n){let i=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(i,e),{ss:i,s:t,rs:r,psk:n,re:(0,rs.u)(32)}}initializeResponder(e,t,r,n){let i=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(i,e),{ss:i,s:t,rs:r,psk:n,re:(0,rs.u)(32)}}writeMessageA(e,t,r){let n=(0,rs.u)(0);void 0!==r?e.e=r:e.e=this.crypto.generateX25519KeyPair();let i=e.e.publicKey;return this.mixHash(e.ss,i),{ne:i,ns:n,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);return this.mixKey(e.ss,this.dh(e.s.privateKey,e.re)),{ne:r,ns:i,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageC(e,t){let r=e.s.publicKey,n=this.encryptAndHash(e.ss,r);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let i=this.encryptAndHash(e.ss,t),s=this.createEmptyKey(),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,messageBuffer:{ne:s,ns:n,ciphertext:i},cs1:o,cs2:a}}readMessageA(e,t){return nz(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(nz(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);n&&nz(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:i,valid:s}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:i,valid:n&&s}}readMessageC(e,t){let{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);if(n&&nz(r)&&(e.rs=r),!e.e)throw Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:i,valid:s}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,plaintext:i,valid:n&&s,cs1:o,cs2:a}}initSession(e,t,r){let n=this.createEmptyKey(),i=(0,rs.u)(32);return{hs:e?this.initializeInitiator(t,r,i,n):this.initializeResponder(t,r,i,n),i:e,mc:0}}sendMessage(e,t,r){let n;if(0===e.mc)n=this.writeMessageA(e.hs,t,r);else if(1===e.mc)n=this.writeMessageB(e.hs,t);else if(2===e.mc){let{h:r,messageBuffer:i,cs1:s,cs2:o}=this.writeMessageC(e.hs,t);n=i,e.h=r,e.cs1=s,e.cs2=o}else if(e.mc>2){if(e.i){if(!e.cs1)throw Error("CS1 (cipher state) is not defined");n=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw Error("CS2 (cipher state) is not defined");n=this.writeMessageRegular(e.cs2,t)}}else throw Error("Session invalid.");return e.mc++,n}recvMessage(e,t){let r=(0,rs.u)(0),n=!1;if(0===e.mc)({plaintext:r,valid:n}=this.readMessageA(e.hs,t));else if(1===e.mc)({plaintext:r,valid:n}=this.readMessageB(e.hs,t));else if(2===e.mc){let{h:i,plaintext:s,valid:o,cs1:a,cs2:l}=this.readMessageC(e.hs,t);r=s,n=o,e.h=i,e.cs1=a,e.cs2=l}return e.mc++,{plaintext:r,valid:n}}}function nY(e,t){t.enabled&&ro&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${(0,r5.B)(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${(0,r5.B)(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function nQ(e,t){t.enabled&&ro&&t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${(0,r5.B)(e.subarray(),"hex")}`)}class nJ{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(e,t,r,n,i,s,o,a,l){this.log=e.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=l??new nW(e,i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){var e,t;if(e=this.session.hs.s,(t=this.log).enabled&&ro&&(t(`LOCAL_STATIC_PUBLIC_KEY ${(0,r5.B)(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${(0,r5.B)(e.privateKey,"hex")}`)),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,(0,rs.u)(0));await this.connection.write(new tR.H(e.ne,e.ciphertext)),this.log.trace("Stage 0 - Initiator finished sending first message."),nY(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");let e=function(e){if(e.length<32)throw Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:(0,rs.u)(0)}}((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new rJ("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),nQ(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){var e,t;this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");let r=function(e){if(e.length<80)throw Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}((await this.connection.read()).subarray()),{plaintext:n,valid:i}=this.xx.recvMessage(this.session,r);if(!i)throw new rJ("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),nQ(this.session.hs.re,this.log),e=this.session.hs.rs,(t=this.log).enabled&&ro&&t(`REMOTE_STATIC_PUBLIC_KEY ${(0,r5.B)(e.subarray(),"hex")}`),this.log.trace("Initiator going to check remote's signature...");try{let e=eD.decode(n);this.remotePeer=this.remotePeer||await nH(e),await nq(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new rQ(`Error occurred while verifying signed payload: ${e.message}`)}this.log.trace("All good with the signature!")}else{this.log.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(new tR.H(e.ne,e.ns,e.ciphertext)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),nY(this.session.hs.e,this.log)}}async finish(){var e,t;if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(new tR.H(e.ns,e.ciphertext)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");let e=function(e){if(e.length<48)throw Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:(0,rs.u)(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}((await this.connection.read()).subarray()),{plaintext:t,valid:r}=this.xx.recvMessage(this.session,e);if(!r)throw new rJ("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{let e=eD.decode(t);this.remotePeer=this.remotePeer||await nH(e),await nq(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new rQ(`Error occurred while verifying signed payload: ${e.message}`)}}e=this.session,(t=this.log).enabled&&ro&&(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${(0,r5.B)(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${(0,r5.B)(e.cs2.k,"hex")}`)):t("Missing cipher state."))}encrypt(e,t){let r=this.getCS(t);return this.xx.encryptWithAd(r,(0,rs.u)(0),e)}decrypt(e,t,r){let n=this.getCS(t,!1);return this.xx.decryptWithAd(n,(0,rs.u)(0),e,r)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new rJ("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}}class nX{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:r,extensions:n,crypto:i,prologueBytes:s}=t,{metrics:o}=e;this.components=e,this.crypto=i??rG,this.extensions=n,this.metrics=o?{xxHandshakeSuccesses:o.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:o.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:o.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:o.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:o.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}:void 0,r?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(r):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??(0,rs.u)(0)}async secureOutbound(e,t,r){let n=rn(t,{lengthEncoder:rW,lengthDecoder:rY,maxDataLength:65535}),i=await this.performHandshake({connection:n,isInitiator:!0,localPeer:e,remotePeer:r}),s=await this.createSecureConnection(n,i);return t.source=s.source,t.sink=s.sink,{conn:t,remoteExtensions:i.remoteExtensions,remotePeer:i.remotePeer}}async secureInbound(e,t,r){let n=rn(t,{lengthEncoder:rW,lengthDecoder:rY,maxDataLength:65535}),i=await this.performHandshake({connection:n,isInitiator:!1,localPeer:e,remotePeer:r}),s=await this.createSecureConnection(n,i);return t.source=s.source,t.sink=s.sink,{conn:t,remotePeer:i.remotePeer,remoteExtensions:i.remoteExtensions}}async performHandshake(e){let t=await nK(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:r,remotePeer:n,connection:i}=e,s=new nJ(this.components,r,t,this.prologue,this.crypto,this.staticKeys,i,n);try{await s.propose(),await s.exchange(),await s.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){if(this.metrics?.xxHandshakeErrors.increment(),e instanceof Error)throw e.message=`Error occurred during XX handshake: ${e.message}`,e}return s}async createSecureConnection(e,t){var r,n;let[i,s]=function(){let e=ri(),t=ri();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),o=e.unwrap();return await (0,tg.z)(i,(r=this.metrics,async function*(e){for await(let n of e)for(let e=0;en.length&&(s=n.length),n instanceof Uint8Array?i=t.encrypt(n.subarray(e,s),t.session):i=t.encrypt(n.sublist(e,s),t.session),r?.encryptedPackets.increment(),yield new tR.H(rW(i.byteLength),i)}}),o,e=>(0,tf.J)(e,{lengthDecoder:rY}),(n=this.metrics,async function*(e){for await(let r of e)for(let e=0;er.length&&(i=r.length),i-16iA(iS(iy,ib),iy),iv=ib(),iw=iA(iS(iv,im,iv),iS(im,iv),iS(iv,im),iv,im);function iE(e){return function(t){let r;try{r=(0,n0.HM)(t)}catch(e){return!1}let n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function iS(...e){function t(t){if(t.length(Array.isArray(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t))&&(t=r),null===r)),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:iE(t),partialMatch:t}}function iA(...e){function t(t){let r=null;return e.some(e=>{let n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)}),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:iE(t),partialMatch:t}}function iI(e){return{toString:function(){return e},matches:function(t){let r;try{r=(0,n0.HM)(t)}catch(e){return!1}let n=r.protoNames();return 1===n.length&&n[0]===e},partialMatch:function(t){return 0===t.length?null:t[0]===e?t.slice(1):null}}}iA(iS(iv,iI("webrtc"),iI("p2p")),iS(iv,iI("webrtc")),iS(ig,iI("webrtc"),iI("p2p")),iS(ig,iI("webrtc")),iI("webrtc"));class i_ extends tQ.L{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");for(let r of(super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[],t.list)){if(!iw.matches(r)){this.log.error("Invalid multiaddr");continue}let e=(0,n0.HM)(r),t=e.getPeerId();if(null==t){this.log.error("Invalid bootstrap multiaddr without peer id");continue}let n={id:(0,nF.jE)(t),multiaddrs:[e]};this.list.push(n)}this._init=t}[nZ.J]=this;[Symbol.toStringTag]="@libp2p/bootstrap";isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL??12e4}}}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var iT=r(5036);let iC=Uint8Array.from([3,1]);(M=(O=eB||(eB={})).AddressInfo||(O.AddressInfo={})).codec=()=>(null==u&&(u=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r})),u),M.encode=e=>(0,ns.LE)(e,M.codec()),M.decode=e=>(0,ns.C6)(e,M.codec()),O.codec=()=>(null==c&&(c=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerId&&e.peerId.byteLength>0&&(t.uint32(10),t.bytes(e.peerId)),null!=e.seq&&0n!==e.seq&&(t.uint32(16),t.uint64(e.seq)),null!=e.addresses)for(let r of e.addresses)t.uint32(26),O.AddressInfo.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={peerId:new Uint8Array(0),seq:0n,addresses:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.peerId=e.bytes();break;case 2:r.seq=e.uint64();break;case 3:r.addresses.push(O.AddressInfo.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r})),c),O.encode=e=>(0,ns.LE)(e,O.codec()),O.decode=e=>(0,ns.C6)(e,O.codec());class iR{static createFromProtobuf=e=>{let t=eB.decode(e);return new iR({peerId:(0,nF.cv)(t.peerId),multiaddrs:(t.addresses??[]).map(e=>(0,n0.HM)(e.multiaddr)),seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=iC;peerId;multiaddrs;seqNumber;domain=iR.DOMAIN;codec=iR.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=eB.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!!(e instanceof iR&&this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&function(e,t){let r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every((e,r)=>t[r].equals(e)))}(this.multiaddrs,e.multiaddrs))}}var ik=r(36408);let iP={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};(U=eN||(eN={})).codec=()=>(null==h&&(h=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r})),h),U.encode=e=>(0,ns.LE)(e,U.codec()),U.decode=e=>(0,ns.C6)(e,U.codec());class iD{static createFromProtobuf=async e=>{let t=eN.decode(e);return new iD({peerId:await (0,nF.y5)(t.publicKey),payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t.privateKey)throw Error("Missing private key");let r=e.domain,n=e.codec,i=e.marshal(),s=iB(r,n,i),o=await (0,ik.r3)(t.privateKey);return new iD({peerId:t,payloadType:n,payload:i,signature:await o.sign(s.subarray())})};static openAndCertify=async(e,t)=>{let r=await iD.createFromProtobuf(e);if(!await r.validate(t))throw new rX.sv("envelope signature is not valid for the given domain",iP.ERR_SIGNATURE_NOT_VALID);return r};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:r,payload:n,signature:i}=e;this.peerId=t,this.payloadType=r,this.payload=n,this.signature=i}marshal(){if(null==this.peerId.publicKey)throw Error("Missing public key");return null==this.marshaled&&(this.marshaled=eN.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return(0,r4.f)(this.marshal(),e.marshal())}async validate(e){let t=iB(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw Error("Missing public key");return(0,ik.lR)(this.peerId.publicKey).verify(t.subarray(),this.signature)}}let iB=(e,t,r)=>{let n=(0,r0.m)(e),i=rt.cv(n.byteLength),s=rt.cv(t.length),o=rt.cv(r.length);return new tR.H(i,n,s,t,o,r)};var iN=r(74369);let iL=e=>e.toString().split("/").slice(1),ix=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),iO=e=>({match:t=>ix(t=>t===e).match(t),pattern:e}),iM=()=>({match:e=>ix(e=>"string"==typeof e).match(e),pattern:"{string}"}),iU=()=>({match:e=>ix(e=>!isNaN(parseInt(e))).match(e),pattern:"{number}"}),iF=()=>({match:e=>{if(e.length<2||"p2p"!==e[0]&&"ipfs"!==e[0]||!(e[1].startsWith("Q")||e[1].startsWith("1")))return!1;try{r1.base58btc.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),iK=()=>({match:e=>{if(e.length<2||"certhash"!==e[0])return!1;try{nt.base64url.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),iV=e=>({match:t=>{let r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),iH=(...e)=>({match:t=>{let r;for(let n of e){let e=n.match(t);!1!==e&&(null==r||e.lengthe.pattern).join(", ")})`}),i$=(...e)=>({match:t=>{for(let r of e){let e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map(e=>e.pattern).join(", ")})`});function iq(...e){function t(t){let r=iL(t);for(let t of e){let e=t.match(r);if(!1===e)return!1;r=e}return r}return{matches:function(e){return!1!==t(e)},exactMatch:function(e){let r=t(e);return!1!==r&&0===r.length}}}let iz=i$(iO("dns4"),iM()),ij=i$(iO("dns6"),iM()),iG=i$(iO("dnsaddr"),iM()),iW=i$(iO("dns"),iM());iq(iz),iq(ij),iq(iG),iq(iH(iW,iG,iz,ij));let iY=i$(iO("ip4"),ix(iN.C)),iQ=i$(iO("ip6"),ix(iN.aY)),iJ=iH(iY,iQ),iX=iH(iJ,iW,iz,ij,iG),iZ=iq(iX);iq(iY),iq(iQ),iq(iJ);let i0=i$(iX,iO("tcp"),iU()),i1=i$(iX,iO("udp"),iU()),i2=iH(i0,i1);iq(i0),iq(i1);let i3=i$(i1,iO("quic")),i4=i$(i1,iO("quic-v1")),i6=iH(i3,i4);iq(i3),iq(i4);let i5=iH(iX,i0,i1,i3,i4),i8=iH(i$(i5,iO("ws"),iV(iF())));iq(i8);let i9=iH(i$(i5,iO("wss"),iV(iF())),i$(i5,iO("tls"),iO("ws"),iV(iF())));iq(i9);let i7=i$(i2,iO("webrtc-direct"),iK(),iV(iK()),iV(iF()));iq(i7);let se=i$(i4,iO("webtransport"),iV(iK()),iV(iK()),iV(iF()));iq(se);let st=iH(i8,i9,i$(i0,iV(iF())),i$(i6,iV(iF())),i$(iX,iV(iF())),i7,se,iF());iq(st);let sr=iq(i$(st,iO("p2p-circuit"),iF()));function sn(e,t){let r=rn(e,t),n={read:async(e,t)=>{let n=await r.read(t);return e.decode(n)},write:async(e,t,n)=>{await r.write(t.encode(e),n)},writeV:async(e,t,n)=>{await r.writeV(e.map(e=>t.encode(e)),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}iq(iH(i$(st,iO("p2p-circuit"),iO("webrtc"),iF()),i$(st,iO("webrtc"),iV(iF())),iO("webrtc"))),iq(iH(i$(iX,iO("tcp"),iU(),iO("http"),iV(iF())),i$(iX,iO("http"),iV(iF())))),iq(iH(i$(iX,iO("tcp"),iH(i$(iO("443"),iO("http")),i$(iU(),iO("https"))),iV(iF())),i$(iX,iO("tls"),iO("http"),iV(iF())),i$(iX,iO("https"),iV(iF()))));var si=r(12471);let ss="object"==typeof window&&"object"==typeof document&&9===document.nodeType,so=si(),sa=ss&&!so,sl=so&&!ss,sc=so&&ss,su=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!so,sh="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV;let sd="undefined"!=typeof navigator&&"ReactNative"===navigator.product;(F=eL||(eL={})).codec=()=>(null==d&&(d=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(let r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(let r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={listenAddrs:[],protocols:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 5:r.protocolVersion=e.string();break;case 6:r.agentVersion=e.string();break;case 1:r.publicKey=e.bytes();break;case 2:r.listenAddrs.push(e.bytes());break;case 4:r.observedAddr=e.bytes();break;case 3:r.protocols.push(e.string());break;case 8:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r})),d),F.encode=e=>(0,ns.LE)(e,F.codec()),F.decode=e=>(0,ns.C6)(e,F.codec());let sp={protocolPrefix:"ipfs",timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0};class sf{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t={}){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.log=e.logger.forComponent("libp2p:identify"),this.identifyProtocolStr=`/${t.protocolPrefix??sp.protocolPrefix}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix??sp.protocolPrefix}/id/push/1.0.0`,this.timeout=t.timeout??sp.timeout,this.maxInboundStreams=t.maxInboundStreams??sp.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??sp.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??sp.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??sp.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??sp.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??sp.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??sp.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??sp.protocolPrefix}/0.1.0`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??sp.runOnConnectionOpen)&&e.events.addEventListener("connection:open",e=>{let t=e.detail;this.identify(t).catch(e=>{this.log.error("error during identify trigged by connection:open",e)})}),e.events.addEventListener("self:peer:update",e=>{this.push().catch(e=>{this.log.error(e)})}),this.host.agentVersion===`${e.nodeInfo.name}/${e.nodeInfo.version}`&&(su||sl?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(sa||sh||sc||sd)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:(0,r0.m)(this.host.agentVersion),ProtocolVersion:(0,r0.m)(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(e=>e.decapsulateCode((0,n0.a_)("p2p").code)),r=new iR({peerId:this.peerId,multiaddrs:t}),n=await iD.seal(r,this.peerId),i=this.registrar.getProtocols(),s=await this.peerStore.get(this.peerId),o=(0,r5.B)(s.metadata.get("AgentVersion")??(0,r0.m)(this.host.agentVersion)),a=(0,r5.B)(s.metadata.get("ProtocolVersion")??(0,r0.m)(this.host.protocolVersion)),l=e.map(async e=>{let r;let s=AbortSignal.timeout(this.timeout);(0,iT.W)(1/0,s);try{r=await e.newStream(this.identifyPushProtocolStr,{signal:s,runOnTransientConnection:this.runOnTransientConnection});let l=sn(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(eL);await l.write({listenAddrs:t.map(e=>e.bytes),signedPeerRecord:n.marshal(),protocols:i,agentVersion:o,protocolVersion:a},{signal:s}),await r.close({signal:s})}catch(e){this.log.error("could not push identify update to peer",e),r?.abort(e)}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(e){if(e.code!==rX.Vc)throw e}})),await this.pushToConnections(e)}async _identify(e,t={}){let r;if(null==t.signal){let e=AbortSignal.timeout(this.timeout);(0,iT.W)(1/0,e),t={...t,signal:e}}try{r=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});let n=sn(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(eL),i=await n.read(t);return await r.close(t),i}catch(e){throw this.log.error("error while reading identify message",e),r?.abort(e),e}}async identify(e,t={}){let r=await this._identify(e,t),{publicKey:n,protocols:i,observedAddr:s}=r;if(null==n)throw new rX.sv("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");let o=await (0,nF.y5)(n);if(!e.remotePeer.equals(o))throw new rX.sv("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new rX.sv("identified peer is our own peer id?","ERR_INVALID_PEER");let a=function(e){if(null!=e&&e.length>0)try{return(0,n0.HM)(e)}catch{}}(s);return this.log("identify completed for peer %p and protocols %o",o,i),this.log("our observed address is %a",a),null!=a&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",a),this.addressManager.addObservedAddr(a)),this.#s(e,r)}async _handleIdentify(e){let{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);(0,iT.W)(1/0,n);try{let e=this.peerId.publicKey??new Uint8Array(0),i=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map(e=>e.decapsulateCode((0,n0.a_)("p2p").code)),o=i.peerRecordEnvelope;if(s.length>0&&null==o){let e=new iR({peerId:this.peerId,multiaddrs:s});o=(await iD.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;iZ.matches(t.remoteAddr)||(a=void 0);let l=sn(r).pb(eL);await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:s.map(e=>e.bytes),signedPeerRecord:o,observedAddr:a,protocols:i.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}async _handlePush(e){let{connection:t,stream:r}=e;try{if(this.peerId.equals(t.remotePeer))throw Error("received push from ourselves?");let e={signal:AbortSignal.timeout(this.timeout)},n=sn(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(eL),i=await n.read(e);await r.close(e),await this.#s(t,i)}catch(e){this.log.error("received invalid message",e),r.abort(e);return}this.log("handled push from %p",t.remotePeer)}async #s(e,t){let r;if(this.log("received identify from %p",e.remotePeer),null==t)throw new rX.sv("message was null or undefined","ERR_INVALID_MESSAGE");let n={};if(t.listenAddrs.length>0&&(n.addresses=t.listenAddrs.map(e=>({isCertified:!1,multiaddr:(0,n0.HM)(e)}))),t.protocols.length>0&&(n.protocols=t.protocols),null!=t.publicKey&&(n.publicKey=t.publicKey,!(await (0,nF.y5)(t.publicKey)).equals(e.remotePeer)))throw new rX.sv("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");if(null!=t.signedPeerRecord){let i;this.log("received signedPeerRecord from %p",e.remotePeer);let s=t.signedPeerRecord,o=await iD.openAndCertify(s,iR.DOMAIN),a=iR.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new rX.sv("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(a.peerId))throw new rX.sv("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{i=await this.peerStore.get(a.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=i&&(n.metadata=i.metadata,null!=i.peerRecordEnvelope)){let e=await iD.createFromProtobuf(i.peerRecordEnvelope),t=iR.createFromProtobuf(e.payload);t.seqNumber>=a.seqNumber&&(this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),a=t,s=i.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(e=>({isCertified:!0,multiaddr:e})),r={seq:a.seqNumber,addresses:a.multiaddrs}}else this.log("%p did not send a signed peer record",e.remotePeer);if(this.log("patching %p with",e.remotePeer,n),await this.peerStore.patch(e.remotePeer,n),null!=t.agentVersion||null!=t.protocolVersion){let r={};null!=t.agentVersion&&(r.AgentVersion=(0,r0.m)(t.agentVersion)),null!=t.protocolVersion&&(r.ProtocolVersion=(0,r0.m)(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,r),await this.peerStore.merge(e.remotePeer,{metadata:r})}let i={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map(e=>(0,n0.HM)(e)),observedAddr:null==t.observedAddr?void 0:(0,n0.HM)(t.observedAddr),protocols:t.protocols,signedPeerRecord:r,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:i}),i}}function sg(e,t){let r=(function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")})(e).return?.();null!=r&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally&&r.catch(e=>{t.error("could not cause iterator to return",e)})}let sm=()=>{let e=Error("Delay aborted");return e.name="AbortError",e},sy=new WeakMap,sb=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:i}={})=>{let s,o,a;if(i?.aborted)return Promise.reject(sm());let l=e??clearTimeout,c=()=>{l(s),a(sm())},u=()=>{i&&i.removeEventListener("abort",c)},h=new Promise((e,i)=>{o=()=>{u(),e(n)},a=i,s=(t??setTimeout)(o,r)});return i&&i.addEventListener("abort",c,{once:!0}),sy.set(h,()=>{l(s),s=null,o()}),h}}();class sv{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??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new sw}async consume(e,t=1,r={}){let n=this.getKey(e),i=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(n,s.consumedPoints,this.blockDuration)),new rX.sv("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let e=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));e=0?r:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return null!=t&&(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)}}class sw{storage;constructor(){this.storage=new Map}incrby(e,t,r){let n=this.storage.get(e);if(null!=n){let e=null!=n.expiresAt?n.expiresAt.getTime()-new Date().getTime():-1;if(null==n.expiresAt||e>0)return n.value+=t,{remainingPoints:0,msBeforeNext:e,consumedPoints:n.value,isFirstInDuration:!1}}return this.set(e,t,r)}set(e,t,r){let n=1e3*r,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);let s={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,s),n>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var sE=r(35605);(K=ex||(ex={}))[K.NEW_STREAM=0]="NEW_STREAM",K[K.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",K[K.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",K[K.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",K[K.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",K[K.RESET_RECEIVER=5]="RESET_RECEIVER",K[K.RESET_INITIATOR=6]="RESET_INITIATOR";let sS=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),sA=Object.freeze({NEW_STREAM:ex.NEW_STREAM,MESSAGE:ex.MESSAGE_INITIATOR,CLOSE:ex.CLOSE_INITIATOR,RESET:ex.RESET_INITIATOR}),sI=Object.freeze({MESSAGE:ex.MESSAGE_RECEIVER,CLOSE:ex.CLOSE_RECEIVER,RESET:ex.RESET_RECEIVER});class s_{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=1048576,t=4194304){this._buffer=new tR.H,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("ERR_MSG_TOO_BIG"===e.code)throw e;break}let{id:e,type:r,length:n,offset:i}=this._headerInfo;if(this._buffer.length-ithis._maxMessageSize)throw Object.assign(Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:s,offset:r+i,length:n}}}function sT(e,t=0){let r,n=0,i=0,s=t,o=e.length;do{if(s>=o||i>49)throw t=0,RangeError("Could not decode varint");r=e.get(s++),n+=i<28?(127&r)<=128);return{value:n,offset:t=s-t}}class sC{_pool;_poolOffset;constructor(){this._pool=(0,rs.E)(10240),this._poolOffset=0}write(e,t){let r=this._pool,n=this._poolOffset;rt.cv(e.id<<3|e.type,r,n),n+=rt.P$(e.id<<3|e.type),(e.type===ex.NEW_STREAM||e.type===ex.MESSAGE_INITIATOR||e.type===ex.MESSAGE_RECEIVER)&&null!=e.data?(rt.cv(e.data.length,r,n),n+=rt.P$(e.data.length)):(rt.cv(0,r,n),n+=rt.P$(0));let i=r.subarray(this._poolOffset,n);10240-n<100?(this._pool=(0,rs.E)(10240),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===ex.NEW_STREAM||e.type===ex.MESSAGE_INITIATOR||e.type===ex.MESSAGE_RECEIVER)&&null!=e.data&&t.append(e.data)}}let sR=new sC;async function*sk(e){for await(let t of e){let e=new tR.H;sR.write(t,e),yield e}}function sP(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class sD{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=(0,t6.Z)(),this.closed=(0,t6.Z)(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=(0,sE.dT)({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new rX.sv(`writable end state is "${this.writeStatus}" not "ready"`,"ERR_SINK_INVALID_STATE");try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if("outbound"===this.direction){let e=this.sendNewStream(t);sP(e)&&await e}let r=()=>{sg(e,this.log)};try{for await(let n of(this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source"),e)){n=n instanceof Uint8Array?new tR.H(n):n;let e=this.sendData(n,t);sP(e)&&(this.sendingData=(0,t6.Z)(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await t8(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await t8(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await t8(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await t8(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();sP(t)&&t.catch(e=>{this.log.error("error sending reset message",e)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;let e=new rX.sv("stream reset","ERR_STREAM_RESET");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if("closing"===this.readStatus||"closed"===this.readStatus){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if("closing"===this.writeStatus||"closed"===this.writeStatus){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class sB extends sD{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?sA:sI,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:sA.NEW_STREAM,data:new tR.H((0,r0.m)(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function sN(e){let t={...e,type:`${sS[e.type]} (${e.type})`};return e.type===ex.NEW_STREAM&&(t.data=(0,r5.B)(e.data instanceof Uint8Array?e.data:e.data.subarray())),(e.type===ex.MESSAGE_INITIATOR||e.type===ex.MESSAGE_RECEIVER)&&(t.data=(0,r5.B)(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class sL{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=(0,sE.dT)({objectMode:!0,onEnd:()=>{for(let e of this._streams.initiators.values())e.destroy();for(let e of this._streams.receivers.values())e.destroy()}}),this.source=(0,tg.z)(this._source,e=>sk(e)),this.closeController=new AbortController,this.rateLimiter=new sv({points:t.disconnectThreshold??5,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw Error("Muxer already closed");let t=this._streamId++;e=null==e?t.toString():e.toString();let r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async e=>e.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){let{id:t,name:r,type:n,registry:i}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new rX.sv("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(i.has(t))throw Error(`${n} stream ${t} already exists!`);let s=async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,sN(e)),this._source.push(e)},o=function(e){let{id:t,name:r,send:n,onEnd:i,type:s="initiator",maxMsgSize:o=1048576}=e;return new sB({id:"initiator"===s?`i${t}`:`r${t}`,streamId:t,name:`${null==r?t:r}`,direction:"initiator"===s?"outbound":"inbound",maxDataSize:o,onEnd:i,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${s}:${t}`)})}({id:t,name:r,send:s,type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,o.protocol),i.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(o)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return i.set(t,o),o}_createSink(){return async e=>{let t=()=>{sg(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{let t=new s_(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let r of e)for(let e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){let{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",sN(e)),e.type===ex.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:ex.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(Error("Too many open streams"))}return}let r=this._newReceiverStream({id:t,name:(0,r5.B)(e.data instanceof Uint8Array?e.data:e.data.subarray())});null!=this._init.onIncomingStream&&this._init.onIncomingStream(r);return}let n=((1&r)==1?this._streams.initiators:this._streams.receivers).get(t);if(null==n){this.log("missing stream %s for message type %s",t,sS[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(Error("Too many messages for missing streams"))}return}let i=this._init.maxStreamBufferSize??4194304;try{switch(r){case ex.MESSAGE_INITIATOR:case ex.MESSAGE_RECEIVER:if(n.sourceReadableLength()>i)throw this._source.push({id:e.id,type:r===ex.MESSAGE_INITIATOR?ex.RESET_RECEIVER:ex.RESET_INITIATOR}),new rX.sv("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case ex.CLOSE_INITIATOR:case ex.CLOSE_RECEIVER:n.remoteCloseWrite();break;case ex.RESET_INITIATOR:case ex.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class sx{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new sL(this.components,{...e,...this._init})}}var sO=r(34018),sM=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(let t of e)return t})();for(let t of e)return t};let sU="ERR_WRONG_PING_ACK";class sF{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnTransientConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnTransientConnection=t.runOnTransientConnection??!0,this.handleMessage=this.handleMessage.bind(this)}async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);let{stream:t}=e,r=Date.now();(0,tg.z)(t,t).catch(t=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,t)}).finally(()=>{let t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)})}async ping(e,t={}){let r;this.log("pinging %p",e);let n=Date.now(),i=(0,sO.Z)(32),s=await this.components.connectionManager.openConnection(e,t),o=()=>{};if(null==t.signal){let e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),o=()=>{r?.abort(new rX.sv("ping timeout",rX.l9))},t.signal?.addEventListener("abort",o,{once:!0});let e=await (0,tg.z)([i],r,async e=>sM(e)),a=Date.now()-n;if(null==e)throw new rX.sv(`Did not receive a ping ack after ${a}ms`,sU);if(!(0,r4.f)(i,e.subarray()))throw new rX.sv(`Received wrong ping ack after ${a}ms`,sU);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),r?.abort(e),e}finally{t.signal?.removeEventListener("abort",o),null!=r&&await r.close()}}}let sK=Symbol.for("@libp2p/transport");(V=eO||(eO={}))[V.FATAL_ALL=0]="FATAL_ALL",V[V.NO_FATAL=1]="NO_FATAL";let sV=[(0,n0.a_)("tcp").code,(0,n0.a_)("dns").code,(0,n0.a_)("dnsaddr").code,(0,n0.a_)("dns4").code,(0,n0.a_)("dns6").code];function sH(e){let t;try{t=(0,n0.a_)("sni").code}catch(e){return null}for(let[r,n]of e)if(r===t&&void 0!==n)return n;return null}function s$(e){return e.some(([e,t])=>e===(0,n0.a_)("tls").code)}function sq(e,t,r){let n=sz[(0,n0.a_)(e).name];if(void 0===n)throw Error(`Can't interpret protocol ${(0,n0.a_)(e).name}`);let i=n(t,r);return e===(0,n0.a_)("ip6").code?`[${i}]`:i}let sz={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`tcp://${sq(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`udp://${sq(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${sq(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${sq(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{let r=s$(t),n=sH(t);if(r&&null!==n)return`https://${n}`;let i=t.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=sq(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${r?"https://":"http://"}${s}`},tls:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return sq(r[0],r[1]??"",t)},sni:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return sq(r[0],r[1]??"",t)},https:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");let n=sq(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{let r=s$(t),n=sH(t);if(r&&null!==n)return`wss://${n}`;let i=t.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=sq(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${r?"wss://":"ws://"}${s}`},wss:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");let n=sq(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${sq(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${sq(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${sq(r[0],r[1]??"",t)}/p2p-webrtc-direct`}};var sj=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise((t,r)=>{function n(){e.removeEventListener("open",i),e.removeEventListener("error",s)}function i(){n(),t()}function s(t){n(),r(t.error??Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",i),e.addEventListener("error",s)})},sG=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(let t of r){try{await sj(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise((t,r)=>{e.addEventListener("close",e=>{e.wasClean||1006===e.code?t():r(Object.assign(Error("ws error"),{event:e}))}),setTimeout(()=>{e.close()})})}),sW=r(44377);function sY(e){return e instanceof ArrayBuffer||e?.constructor?.name==="ArrayBuffer"&&"number"==typeof e?.byteLength}var sQ=e=>{let t;e.binaryType="arraybuffer";let r=async()=>{await new Promise((r,n)=>{if(i){r();return}if(null!=t){n(t);return}let s=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{s(r)},a=t=>{s(()=>{n(t.error??Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener("open",o),e.addEventListener("error",a)})},n=async function*(){let t=new sW.zN(({push:t,stop:r,fail:n})=>{let i=e=>{let r=null;"string"==typeof e.data&&(r=(0,r0.m)(e.data)),sY(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},s=e=>{n(e.error??Error("Socket error"))};return e.addEventListener("message",i),e.addEventListener("error",s),e.addEventListener("close",r),()=>{e.removeEventListener("message",i),e.removeEventListener("error",s),e.removeEventListener("close",r)}},{highWaterMark:1/0});for await(let e of(await r(),t))yield sY(e)?new Uint8Array(e):e}(),i=1===e.readyState;return e.addEventListener("open",()=>{i=!0,t=null}),e.addEventListener("close",()=>{i=!1,t=null}),e.addEventListener("error",r=>{i||(t=r.error??Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(n,{connected:r})},sJ=(e,t)=>{t=t??{};let r=sQ(e),n=t.remoteAddress,i=t.remotePort;if(null!=e.url)try{let t=new URL(e.url);n=t.hostname,i=parseInt(t.port,10)}catch{}if(null==n||null==i)throw Error("Remote connection did not have address and/or port");return{sink:sG(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{(e.readyState===e.CONNECTING||e.readyState===e.OPEN)&&await new Promise(t=>{e.addEventListener("close",()=>{t()}),e.close()})},destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:i,socket:e}},sX=WebSocket;let sZ={"http:":"ws:","https:":"wss:"};var s0=(e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){let r=t.protocol??"ws:",n=t.host,i=null!=t.port&&n?.endsWith(`:${t.port}`)!==!0?`:${t.port}`:"";e=`${r}//${n}${i}${e}`}let r=new URL(e);for(let[e,t]of Object.entries(sZ))r.protocol===e&&(r.protocol=t);return r};function s1(e){return e.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return ir.matches(t)||is.matches(t)})}class s2{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[sK]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let r=function(e,t,r){let n=r.logger.forComponent("libp2p:websockets:maconn"),i={log:n,async sink(t){try{await e.sink(async function*(){for await(let e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){let r=Date.now();if(null==t.signal){let e=AbortSignal.timeout(500);t={...t,signal:e}}let s=()=>{let{host:e,port:t}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new rX.sv("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),i.timeline.close=Date.now()}},abort(t){let{host:r,port:s}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,s,t),e.destroy(),i.timeline.close=Date.now()}};return e.socket.addEventListener("close",()=>{null==i.timeline.close&&(i.timeline.close=Date.now())},{once:!0}),i}(await this._connect(e,t),e,{logger:this.logger});this.log("new outbound connection %s",r.remoteAddr);let n=await t.upgrader.upgradeOutbound(r);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){var r,n;let i;if(t?.signal?.aborted===!0)throw new rX._L;let s=e.toOptions();this.log("dialing %s:%s",s.host,s.port);let o=(0,t6.Z)(),a=(r=function(e,t){let r=(0,n0.HM)(e).stringTuples(),n=r.pop();if(void 0===n)throw Error("Unexpected end of multiaddr");let i=(0,n0.a_)(n[0]),s=sz[i.name];if(null==s)throw Error(`No interpreter found for ${i.name}`);let o=s(n[1]??"",r);return sV.includes(n[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===n[1]?`https://${o}`:`http://${o}`),(o.startsWith("http://")||o.startsWith("https://"))&&(o=new URL(o).toString()).endsWith("/")&&(o=o.substring(0,o.length-1)),o}(e),n=(n=this.init)??{},sJ(new sX(s0(r,"undefined"==typeof window?void 0:window.location).toString(),n.websocket),n));if(a.socket.addEventListener("error",()=>{let t=new rX.sv(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),o.reject(t)}),null==t.signal)return await Promise.race([a.connected(),o.promise]),this.log("connected %s",e),a;let l=new Promise((e,r)=>{if(i=()=>{r(new rX._L),a.close().catch(e=>{this.log.error("error closing raw socket",e)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([l,o.promise,a.connected()])}finally{null!=i&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),a}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}({logger:this.logger},{...this.init,...e})}listenFilter(e){return(e=Array.isArray(e)?e:[e],this.init?.filter!=null)?this.init?.filter(e):sa||sh?e.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return is.matches(t)}):s1(e)}dialFilter(e){return this.listenFilter(e)}}let s3="StrictSign",s4="StrictNoSign";(H=eM||(eM={})).Accept="accept",H.Ignore="ignore",H.Reject="reject";let s6="/floodsub/1.0.0",s5="/meshsub/1.0.0",s8="/meshsub/1.1.0",s9={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};(q=($=eU||(eU={})).SubOpts||($.SubOpts={})).codec=()=>(null==f&&(f=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.subscribe&&(t.uint32(8),t.bool(e.subscribe)),null!=e.topic&&(t.uint32(18),t.string(e.topic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.subscribe=e.bool();break;case 2:n.topic=e.string();break;default:e.skipType(7&t)}}return n})),f),q.encode=e=>(0,ns.LE)(e,q.codec()),q.decode=(e,t)=>(0,ns.C6)(e,q.codec(),t),(z=$.Message||($.Message={})).codec=()=>(null==g&&(g=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.from&&(t.uint32(10),t.bytes(e.from)),null!=e.data&&(t.uint32(18),t.bytes(e.data)),null!=e.seqno&&(t.uint32(26),t.bytes(e.seqno)),null!=e.topic&&""!==e.topic&&(t.uint32(34),t.string(e.topic)),null!=e.signature&&(t.uint32(42),t.bytes(e.signature)),null!=e.key&&(t.uint32(50),t.bytes(e.key)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={topic:""},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.from=e.bytes();break;case 2:n.data=e.bytes();break;case 3:n.seqno=e.bytes();break;case 4:n.topic=e.string();break;case 5:n.signature=e.bytes();break;case 6:n.key=e.bytes();break;default:e.skipType(7&t)}}return n})),g),z.encode=e=>(0,ns.LE)(e,z.codec()),z.decode=(e,t)=>(0,ns.C6)(e,z.codec(),t),(j=$.ControlMessage||($.ControlMessage={})).codec=()=>(null==m&&(m=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.ihave)for(let r of e.ihave)t.uint32(10),$.ControlIHave.codec().encode(r,t);if(null!=e.iwant)for(let r of e.iwant)t.uint32(18),$.ControlIWant.codec().encode(r,t);if(null!=e.graft)for(let r of e.graft)t.uint32(26),$.ControlGraft.codec().encode(r,t);if(null!=e.prune)for(let r of e.prune)t.uint32(34),$.ControlPrune.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={ihave:[],iwant:[],graft:[],prune:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:if(r.limits?.ihave!=null&&n.ihave.length===r.limits.ihave)throw new ns.sv('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");n.ihave.push($.ControlIHave.codec().decode(e,e.uint32()));break;case 2:if(r.limits?.iwant!=null&&n.iwant.length===r.limits.iwant)throw new ns.sv('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");n.iwant.push($.ControlIWant.codec().decode(e,e.uint32()));break;case 3:if(r.limits?.graft!=null&&n.graft.length===r.limits.graft)throw new ns.sv('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");n.graft.push($.ControlGraft.codec().decode(e,e.uint32()));break;case 4:if(r.limits?.prune!=null&&n.prune.length===r.limits.prune)throw new ns.sv('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");n.prune.push($.ControlPrune.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return n})),m),j.encode=e=>(0,ns.LE)(e,j.codec()),j.decode=(e,t)=>(0,ns.C6)(e,j.codec(),t),(G=$.ControlIHave||($.ControlIHave={})).codec=()=>(null==y&&(y=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.messageIDs)for(let r of e.messageIDs)t.uint32(18),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messageIDs:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.topicID=e.string();break;case 2:if(r.limits?.messageIDs!=null&&n.messageIDs.length===r.limits.messageIDs)throw new ns.sv('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes());break;default:e.skipType(7&t)}}return n})),y),G.encode=e=>(0,ns.LE)(e,G.codec()),G.decode=(e,t)=>(0,ns.C6)(e,G.codec(),t),(W=$.ControlIWant||($.ControlIWant={})).codec=()=>(null==b&&(b=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messageIDs)for(let r of e.messageIDs)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messageIDs:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(r.limits?.messageIDs!=null&&n.messageIDs.length===r.limits.messageIDs)throw new ns.sv('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes())}else e.skipType(7&t)}return n})),b),W.encode=e=>(0,ns.LE)(e,W.codec()),W.decode=(e,t)=>(0,ns.C6)(e,W.codec(),t),(Y=$.ControlGraft||($.ControlGraft={})).codec=()=>(null==v&&(v=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.topicID=e.string():e.skipType(7&t)}return n})),v),Y.encode=e=>(0,ns.LE)(e,Y.codec()),Y.decode=(e,t)=>(0,ns.C6)(e,Y.codec(),t),(Q=$.ControlPrune||($.ControlPrune={})).codec=()=>(null==w&&(w=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.peers)for(let r of e.peers)t.uint32(18),$.PeerInfo.codec().encode(r,t);null!=e.backoff&&(t.uint32(24),t.uint64Number(e.backoff)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={peers:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.topicID=e.string();break;case 2:if(r.limits?.peers!=null&&n.peers.length===r.limits.peers)throw new ns.sv('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");n.peers.push($.PeerInfo.codec().decode(e,e.uint32()));break;case 3:n.backoff=e.uint64Number();break;default:e.skipType(7&t)}}return n})),w),Q.encode=e=>(0,ns.LE)(e,Q.codec()),Q.decode=(e,t)=>(0,ns.C6)(e,Q.codec(),t),(J=$.PeerInfo||($.PeerInfo={})).codec=()=>(null==E&&(E=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.peerID&&(t.uint32(10),t.bytes(e.peerID)),null!=e.signedPeerRecord&&(t.uint32(18),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.peerID=e.bytes();break;case 2:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n})),E),J.encode=e=>(0,ns.LE)(e,J.codec()),J.decode=(e,t)=>(0,ns.C6)(e,J.codec(),t),$.codec=()=>(null==p&&(p=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.subscriptions)for(let r of e.subscriptions)t.uint32(10),$.SubOpts.codec().encode(r,t);if(null!=e.messages)for(let r of e.messages)t.uint32(18),$.Message.codec().encode(r,t);null!=e.control&&(t.uint32(26),$.ControlMessage.codec().encode(e.control,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={subscriptions:[],messages:[]},i=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:if(r.limits?.subscriptions!=null&&n.subscriptions.length===r.limits.subscriptions)throw new ns.sv('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");n.subscriptions.push($.SubOpts.codec().decode(e,e.uint32()));break;case 2:if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new ns.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push($.Message.codec().decode(e,e.uint32()));break;case 3:n.control=$.ControlMessage.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return n})),p),$.encode=e=>(0,ns.LE)(e,$.codec()),$.decode=(e,t)=>(0,ns.C6)(e,$.codec(),t);class s7{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let e=0;e{let n=this.msgs.get(r.msgIdStr);if(n?.validated&&e.has(r.topic)){let e=t.get(r.topic);null==e&&(e=[],t.set(r.topic,e)),e.push(r.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(null==t)return null;!t.validated&&this.notValidatedCount--;let{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(e=>{let t=this.msgs.get(e.msgIdStr);null!=t&&(this.msgs.delete(e.msgIdStr),!t.validated&&this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return null==t?null:(this.msgs.delete(e),t)}}function oe(e){switch(e){case eM.Ignore:return eV.Ignore;case eM.Reject:return eV.Reject;default:throw Error("Unreachable")}}(X=eF||(eF={})).StrictSign="StrictSign",X.StrictNoSign="StrictNoSign",(Z=eK||(eK={}))[Z.Signing=0]="Signing",Z[Z.Anonymous=1]="Anonymous",(ee=eV||(eV={})).Error="error",ee.Ignore="ignore",ee.Reject="reject",ee.Blacklisted="blacklisted",(et=eH||(eH={})).InvalidSignature="invalid_signature",et.InvalidSeqno="invalid_seqno",et.InvalidPeerId="invalid_peerid",et.SignaturePresent="signature_present",et.SeqnoPresent="seqno_present",et.FromPresent="from_present",et.TransformFailed="transform_failed",(er=e$||(e$={})).duplicate="duplicate",er.invalid="invalid",er.valid="valid",(en=eq||(eq={})).forward="forward",en.publish="publish",(ei=ez||(ez={})).Fanout="fanout",ei.Random="random",ei.Subscribed="subscribed",ei.Outbound="outbound",ei.NotEnough="not_enough",ei.Opportunistic="opportunistic",(es=ej||(ej={})).Dc="disconnected",es.BadScore="bad_score",es.Prune="prune",es.Excess="excess",(eo=eG||(eG={})).GraftBackoff="graft_backoff",eo.BrokenPromise="broken_promise",eo.MessageDeficit="message_deficit",eo.IPColocation="IP_colocation",(ea=eW||(eW={})).LowScore="low_score",ea.MaxIhave="max_ihave",ea.MaxIasked="max_iasked",(el=eY||(eY={})).graylist="graylist",el.publish="publish",el.gossip="gossip",el.mesh="mesh";let ot="ERR_INVALID_PEER_SCORE_PARAMS",or={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:36e5},on={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3},oi={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function os(e,t,r=()=>!0){let n=new Set;if(t<=0)return n;for(let i of e){if(n.size>=t)break;r(i)&&(n.add(i),e.delete(i))}return n}class oo extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return void 0===t&&(t=this.getDefault(),this.set(e,t)),t}}function oa(e,t,r,n){let i=0;Object.entries(t.topics).forEach(([e,t])=>{let n=r.topics[e];if(void 0===n)return;let s=0;if(t.inMesh){let e=t.meshTime/n.timeInMeshQuantum;e>n.timeInMeshCap&&(e=n.timeInMeshCap),s+=e*n.timeInMeshWeight}let o=t.firstMessageDeliveries;if(o>n.firstMessageDeliveriesCap&&(o=n.firstMessageDeliveriesCap),s+=o*n.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries0&&i>r.topicScoreCap&&(i=r.topicScoreCap);let s=r.appSpecificScore(e);if(i+=s*r.appSpecificWeight,t.knownIPs.forEach(e=>{if(r.IPColocationFactorWhitelist.has(e))return;let t=n.get(e),s=null!=t?t.size:0;if(s>r.IPColocationFactorThreshold){let e=s-r.IPColocationFactorThreshold;i+=e*e*r.IPColocationFactorWeight}}),t.behaviourPenalty>r.behaviourPenaltyThreshold){let e=t.behaviourPenalty-r.behaviourPenaltyThreshold;i+=e*e*r.behaviourPenaltyWeight}return i}var ol=r(64170);(ec=eQ||(eQ={}))[ec.unknown=0]="unknown",ec[ec.valid=1]="valid",ec[ec.invalid=2]="invalid",ec[ec.ignored=3]="ignored";class oc{records;queue;constructor(){this.records=new Map,this.queue=new ol}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:eQ.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;null!=t&&t.expirenew Set);scoreCache=new Map;deliveryRecords=new oc;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,function(e){for(let[t,r]of Object.entries(e.topics))try{(function(e){if(e.topicWeight<0)throw new rX.sv("invalid topic weight; must be >= 0",ot);if(0===e.timeInMeshQuantum)throw new rX.sv("invalid TimeInMeshQuantum; must be non zero",ot);if(e.timeInMeshWeight<0)throw new rX.sv("invalid TimeInMeshWeight; must be positive (or 0 to disable)",ot);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new rX.sv("invalid TimeInMeshQuantum; must be positive",ot);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new rX.sv("invalid TimeInMeshCap; must be positive",ot);if(e.firstMessageDeliveriesWeight<0)throw new rX.sv("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",ot);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new rX.sv("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",ot);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new rX.sv("invalid FirstMessageDeliveriesCap; must be positive",ot);if(e.meshMessageDeliveriesWeight>0)throw new rX.sv("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",ot);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new rX.sv("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",ot);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new rX.sv("invalid MeshMessageDeliveriesCap; must be positive",ot);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new rX.sv("invalid MeshMessageDeliveriesThreshold; must be positive",ot);if(e.meshMessageDeliveriesWindow<0)throw new rX.sv("invalid MeshMessageDeliveriesWindow; must be non-negative",ot);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new rX.sv("invalid MeshMessageDeliveriesActivation; must be at least 1s",ot);if(e.meshFailurePenaltyWeight>0)throw new rX.sv("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",ot);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new rX.sv("invalid MeshFailurePenaltyDecay; must be between 0 and 1",ot);if(e.invalidMessageDeliveriesWeight>0)throw new rX.sv("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",ot);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new rX.sv("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",ot)})(r)}catch(e){throw new rX.sv(`invalid score parameters for topic ${t}: ${e.message}`,ot)}if(e.topicScoreCap<0)throw new rX.sv("invalid topic score cap; must be positive (or 0 for no cap)",ot);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new rX.sv("missing application specific score function",ot);if(e.IPColocationFactorWeight>0)throw new rX.sv("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",ot);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new rX.sv("invalid IPColocationFactorThreshold; must be at least 1",ot);if(e.behaviourPenaltyWeight>0)throw new rX.sv("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",ot);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new rX.sv("invalid BehaviourPenaltyDecay; must be between 0 and 1",ot);if(e.decayInterval<1e3)throw new rX.sv("invalid DecayInterval; must be at least 1s",ot);if(e.decayToZero<=0||e.decayToZero>=1)throw new rX.sv("invalid DecayToZero; must be between 0 and 1",ot)}(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??oa,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(null!=this._backgroundInterval){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(null==this._backgroundInterval){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return null!=t?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,n)=>{if(!r.connected){e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(r.topics).forEach(([r,n])=>{let i=this.params.topics[r];void 0!==i&&(n.firstMessageDeliveries*=i.firstMessageDeliveriesDecay,n.firstMessageDeliveriesi.meshMessageDeliveriesActivation&&(n.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenaltyr)return n.score;this.metrics?.scoreFnRuns.inc();let i=this.computeScore(e,t,this.params,this.peerIPs),s=r+this.scoreCacheValidityMs;return null!=n?(this.metrics?.scoreCachedDelta.observe(Math.abs(i-n.score)),n.score=i,n.cacheUntil=s):this.scoreCache.set(e,{score:i,cacheUntil:s}),i}addPenalty(e,t,r){let n=this.peerStats.get(e);null!=n&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let r=this.peerStats.get(e);null!=r&&r.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let r=this.peerStats.get(e);null!=r&&r.knownIPs.delete(t);let n=this.peerIPs.get(t);null!=n&&(n.delete(e),0===n.size&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(null!=t){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([e,t])=>{t.firstMessageDeliveries=0;let r=this.params.topics[e].meshMessageDeliveriesThreshold;if(t.inMesh&&t.meshMessageDeliveriesActive&&t.meshMessageDeliveries{t!==e.toString()&&this.markDuplicateMessageDelivery(t,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case eV.Error:this.markInvalidMessageDelivery(e,r);return;case eV.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==eQ.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,eQ[i.status]);return}if(n===eV.Ignore){i.status=eQ.ignored,i.peers.clear();return}i.status=eQ.invalid,this.markInvalidMessageDelivery(e,r),i.peers.forEach(e=>{this.markInvalidMessageDelivery(e,r)}),i.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case eQ.unknown:n.peers.add(e);break;case eQ.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case eQ.invalid:this.markInvalidMessageDelivery(e,r);case eQ.ignored:}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(null!=r){let e=this.getPtopicStats(r,t);null!=e&&(e.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(null!=r){let e=this.getPtopicStats(r,t);if(null!=e){let r=this.params.topics[t].firstMessageDeliveriesCap;e.firstMessageDeliveries=Math.min(r,e.firstMessageDeliveries+1),e.inMesh&&(r=this.params.topics[t].meshMessageDeliveriesCap,e.meshMessageDeliveries=Math.min(r,e.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(null!=n){let e=void 0!==r?Date.now():0,i=this.getPtopicStats(n,t);if(null!=i&&i.inMesh){let n=this.params.topics[t];if(void 0!==r){let i=e-r,s=i>n.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,i,s),s)return}let s=n.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(s,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let t=this.peerIPs.get(r);null!=t&&(t.delete(e),0===t.size&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return void 0!==r?r:void 0!==this.params.topics[t]?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}}class oh{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,r){this.rawStream=e,this.pushable=(0,sE.dT)(),this.closeController=new AbortController,this.maxBufferSize=r.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(t=>{e.abort(t)})}),(0,tg.z)(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(tf.c.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}}class od{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(t=>{e.abort(t)})}),this.source=(0,tg.z)(this.rawStream,e=>(0,tf.J)(e,t))}async close(){this.closeController.abort()}}class op{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let r=Math.floor(Math.random()*t.length),n=t[r],i=this.msgIdToStrFn(n),s=this.promises.get(i);null==s&&(s=new Map,this.promises.set(i,s));let o=Date.now();s.has(e)||(s.set(e,o+this.gossipsubIWantFollowupMs),null==this.metrics||(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(i)||this.requestMsByMsg.set(i,o)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,i)=>{n.forEach((i,s)=>{iMath.floor(Math.random()*Math.floor(e.length));for(let r=0;r{let r=(0,r0.m)(t.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(e.length+r.length);return n.set(e,0),n.set(r,e.length),n};function oS(e){if("signed"!==e.type)throw Error("expected signed message type");if(null==e.sequenceNumber)throw Error("missing seqno field");return oE(e.from.toBytes(),e.sequenceNumber)}async function oA(e){return r3.sha256.encode(e.data)}var oI=r(88695);async function o_(e,t){switch(e){case s3:{if(null==t)throw Error("Must provide PeerId");if(null==t.privateKey)throw Error("Cannot sign message, no private key present");if(null==t.publicKey)throw Error("Cannot sign message, no public key present");let e=await (0,ik.r3)(t.privateKey);return{type:eK.Signing,author:t,key:t.publicKey,privateKey:e}}case s4:return{type:eK.Anonymous};default:throw Error(`Unknown signature policy "${e}"`)}}(eu=eJ||(eJ={}))[eu.ip4=4]="ip4",eu[eu.ip6=41]="ip6";class oT{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return!!this.entries.has(e)||(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs=Date.now()?t.value:void 0}clear(){this.entries.clear()}}(eh=eX||(eX={}))[eh.started=0]="started",eh[eh.stopped=1]="stopped";class oC extends tQ.L{globalSignaturePolicy;multicodecs=[s8,s5];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=(0,sE.dT)({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;components;directPeerInitial=null;static multicodec=s8;opts;decodeRpcLimits;metrics;status={code:eX.stopped};maxInboundStreams;maxOutboundStreams;runOnTransientConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,...t,scoreParams:function(e={}){return{...or,...e,topics:null!=e.topics?Object.entries(e.topics).reduce((e,[t,r])=>(e[t]=function(e={}){return{...on,...e}}(r),e),{}):{}}}(t.scoreParams),scoreThresholds:function(e={}){return{...oi,...e}}(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??s9,this.globalSignaturePolicy=r.globalSignaturePolicy??s3,r.fallbackToFloodsub&&this.multicodecs.push(s6),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(e=>e.id.toString())),this.seenCache=new oT({validityMs:r.seenTTL}),this.publishedMessageIds=new oT({validityMs:r.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case s3:this.msgIdFn=oS;break;case s4:this.msgIdFn=oA;break;default:throw Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new oT({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??ov,this.mcache=t.messageCache??new s7(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),null!=t.dataTransform&&(this.dataTransform=t.dataTransform),null!=t.metricsRegister){var n,i,s;if(null==t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");let e=Math.max(...Object.values(r.scoreParams.topics).map(e=>e.meshMessageDeliveriesWindow),1e3),o=(n=t.metricsRegister,i=t.metricsTopicStrToLabel,s={gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:e/1e3},{protocolsEnabled:n.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:n.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:n.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:n.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:n.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:n.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:n.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:n.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:n.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:n.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:n.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:n.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:n.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:n.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:n.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:n.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:n.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:n.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:n.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:n.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:n.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:n.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:n.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:n.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:n.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:n.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:n.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:n.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:n.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:n.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:n.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:n.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:n.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:n.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:n.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:n.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:n.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:n.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:n.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:n.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:n.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:n.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:n.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:n.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:n.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:n.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:n.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:n.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:n.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:n.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:n.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:n.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:n.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:n.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:n.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:n.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:n.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:n.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:n.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:n.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*s.maxMeshMessageDeliveriesWindowSec,.5*s.maxMeshMessageDeliveriesWindowSec,Number(s.maxMeshMessageDeliveriesWindowSec),2*s.maxMeshMessageDeliveriesWindowSec,4*s.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:n.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:n.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:n.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:n.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:n.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:n.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:n.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:n.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:n.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:n.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:n.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*s.behaviourPenaltyThreshold,.5*s.behaviourPenaltyThreshold,Number(s.behaviourPenaltyThreshold),2*s.behaviourPenaltyThreshold,4*s.behaviourPenaltyThreshold]}),ihaveRcvIgnored:n.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:n.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:n.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:n.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:n.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:n.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:n.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:n.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:n.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:n.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:n.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:n.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*s.gossipPromiseExpireSec,Number(s.gossipPromiseExpireSec),2*s.gossipPromiseExpireSec,4*s.gossipPromiseExpireSec]}),iwantPromiseUntracked:n.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:n.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:n.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:n.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:n.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:n.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:n.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:i,toTopic(e){return this.topicStrToLabel.get(e)??e},onJoin(e){this.topicSubscriptionStatus.set({topicStr:e},1),this.meshPeerCounts.set({topicStr:e},0)},onLeave(e){this.topicSubscriptionStatus.set({topicStr:e},0),this.meshPeerCounts.set({topicStr:e},0)},onAddToMesh(e,t,r){let n=this.toTopic(e);switch(t){case ez.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:n},r);break;case ez.Random:this.meshPeerInclusionEventsRandom.inc({topic:n},r);break;case ez.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:n},r);break;case ez.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:n},r);break;case ez.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:n},r);break;case ez.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:n},r);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:n},r)}},onRemoveFromMesh(e,t,r){let n=this.toTopic(e);switch(t){case ej.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:n},r);break;case ej.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:n},r);break;case ej.Prune:this.meshPeerChurnEventsPrune.inc({topic:n},r);break;case ej.Excess:this.meshPeerChurnEventsExcess.inc({topic:n},r);break;default:this.meshPeerChurnEventsUnknown.inc({topic:n},r)}},onReportValidation(e,t,r){if(this.asyncValidationMcacheHit.inc({hit:null!=e?"hit":"miss"}),null!=e){let r=this.toTopic(e.message.topic);switch(t){case eM.Accept:this.acceptedMessagesTotal.inc({topic:r});break;case eM.Ignore:this.ignoredMessagesTotal.inc({topic:r});break;case eM.Reject:this.rejectedMessagesTotal.inc({topic:r});break;default:this.unknownValidationResultsTotal.inc({topic:r})}}null!=r?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-r)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(e){this.scoringPenalties.inc({penalty:e},1)},onIhaveRcv(e,t,r){let n=this.toTopic(e);this.ihaveRcvMsgids.inc({topic:n},t),this.ihaveRcvNotSeenMsgids.inc({topic:n},r)},onIwantRcv(e,t){for(let[t,r]of e){let e=this.toTopic(t);this.iwantRcvMsgids.inc({topic:e},r)}this.iwantRcvDonthaveMsgids.inc(t)},onForwardMsg(e,t){let r=this.toTopic(e);this.msgForwardCount.inc({topic:r},1),this.msgForwardPeers.inc({topic:r},t)},onPublishMsg(e,t,r,n,i){let s=this.toTopic(e);this.msgPublishCount.inc({topic:s},1),this.msgPublishBytes.inc({topic:s},r*n),this.msgPublishPeersByTopic.inc({topic:s},r),this.directPeersPublishedTotal.inc({topic:s},t.direct),this.floodsubPeersPublishedTotal.inc({topic:s},t.floodsub),this.meshPeersPublishedTotal.inc({topic:s},t.mesh),this.fanoutPeersPublishedTotal.inc({topic:s},t.fanout),this.msgPublishTime.observe({topic:s},i/1e3)},onMsgRecvPreValidation(e){let t=this.toTopic(e);this.msgReceivedPreValidation.inc({topic:t},1)},onMsgRecvError(e){let t=this.toTopic(e);this.msgReceivedError.inc({topic:t},1)},onPrevalidationResult(e,t){let r=this.toTopic(e);switch(t){case e$.duplicate:this.prevalidationDuplicateTotal.inc({topic:r});break;case e$.invalid:this.prevalidationInvalidTotal.inc({topic:r});break;case e$.valid:this.prevalidationValidTotal.inc({topic:r});break;default:this.prevalidationUnknownTotal.inc({topic:r})}},onMsgRecvInvalid(e,t){let r=this.toTopic(e),n=t.reason===eV.Error?t.error:t.reason;this.msgReceivedInvalid.inc({error:n},1),this.msgReceivedInvalidByTopic.inc({topic:r},1)},onDuplicateMsgDelivery(e,t,r){let n=this.toTopic(e);this.duplicateMsgDeliveryDelay.observe({topic:n},t/1e3),r&&this.duplicateMsgLateDelivery.inc({topic:n},1)},onPublishDuplicateMsg(e){let t=this.toTopic(e);this.duplicateMsgIgnored.inc({topic:t},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(e,t){this.rpcRecvBytes.inc(t),this.rpcRecvCount.inc(1),null!=e.subscriptions&&this.rpcRecvSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcRecvMessage.inc(e.messages.length),null!=e.control&&(this.rpcRecvControl.inc(1),null!=e.control.ihave&&this.rpcRecvIHave.inc(e.control.ihave.length),null!=e.control.iwant&&this.rpcRecvIWant.inc(e.control.iwant.length),null!=e.control.graft&&this.rpcRecvGraft.inc(e.control.graft.length),null!=e.control.prune&&this.rpcRecvPrune.inc(e.control.prune.length))},onRpcSent(e,t){if(this.rpcSentBytes.inc(t),this.rpcSentCount.inc(1),null!=e.subscriptions&&this.rpcSentSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcSentMessage.inc(e.messages.length),null!=e.control){let t=e.control.ihave?.length??0,r=e.control.iwant?.length??0,n=e.control.graft?.length??0,i=e.control.prune?.length??0;t>0&&this.rpcSentIHave.inc(t),r>0&&this.rpcSentIWant.inc(r),n>0&&this.rpcSentGraft.inc(n),i>0&&this.rpcSentPrune.inc(i),(t>0||r>0||n>0||i>0)&&this.rpcSentControl.inc(1)}},registerScores(e,t){let r=0,n=0,i=0,s=0;for(let o of e)o>=t.graylistThreshold&&r++,o>=t.publishThreshold&&n++,o>=t.gossipThreshold&&i++,o>=0&&s++;this.peersByScoreThreshold.set({threshold:eY.graylist},r),this.peersByScoreThreshold.set({threshold:eY.publish},n),this.peersByScoreThreshold.set({threshold:eY.gossip},i),this.peersByScoreThreshold.set({threshold:eY.mesh},s),this.score.set(e)},registerScoreWeights(e){for(let[t,r]of e.byTopic)this.scoreWeights.set({topic:t,p:"p1"},r.p1w),this.scoreWeights.set({topic:t,p:"p2"},r.p2w),this.scoreWeights.set({topic:t,p:"p3"},r.p3w),this.scoreWeights.set({topic:t,p:"p3b"},r.p3bw),this.scoreWeights.set({topic:t,p:"p4"},r.p4w);this.scoreWeights.set({p:"p5"},e.p5w),this.scoreWeights.set({p:"p6"},e.p6w),this.scoreWeights.set({p:"p7"},e.p7w)},registerScorePerMesh(e,t){let r=new Map;for(let[n,i]of(e.forEach((e,t)=>{let n=this.topicStrToLabel.get(t)??"unknown",i=r.get(n);null==i&&(i=new Set,r.set(n,i)),e.forEach(e=>i?.add(e))}),r)){let e=[];i.forEach(r=>{e.push(t.get(r)??0)}),this.scorePerMesh.set({topic:n},e)}}});for(let e of(o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)}),this.multicodecs))o.protocolsEnabled.set({protocol:e},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new op(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new ou(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnTransientConnection=t.runOnTransientConnection,this.allowedTopics=null!=r.allowedTopics?new Set(r.allowedTopics):null}getPeers(){return[...this.peers.keys()].map(e=>(0,nF.jE)(e))}isStarted(){return this.status.code===eX.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await o_(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=(0,sE.dT)({objectMode:!0}),(0,tg.z)(this.outboundInflightQueue,async e=>{for await(let{peerId:t,connection:r}of e)await this.createOutboundStream(t,r)}).catch(e=>{this.log.error("outbound inflight queue error",e)}),await Promise.all(this.opts.directPeers.map(async e=>{await this.components.peerStore.merge(e.id,{multiaddrs:e.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async t=>e.handle(t,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnTransient:this.runOnTransientConnection},r=await Promise.all(this.multicodecs.map(async r=>e.register(r,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:eX.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async e=>this.connect(e)))}).catch(e=>{this.log(e)})},1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==eX.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:eX.stopped};let t=this.components.registrar;await Promise.all(this.multicodecs.map(async e=>t.unhandle(e))),e.forEach(e=>{t.unregister(e)}),this.outboundInflightQueue.end();let r=[];for(let e of this.streamsOutbound.values())r.push(e.close());for(let e of(this.streamsOutbound.clear(),this.streamsInbound.values()))r.push(e.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),null!=this.heartbeatTimer&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),null!=this.fastMsgIdCache&&this.fastMsgIdCache.clear(),null!=this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),this.isStarted()&&"open"===t.status&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!(!this.peers.has(r)||this.streamsOutbound.has(r)))try{let n=new oh(await t.newStream(this.multicodecs,{runOnTransientConnection:this.runOnTransientConnection}),e=>{this.log.error("outbound pipe error",e)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,n);let i=n.protocol;i===s6&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:i},1),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(e){this.log.error("createOutboundStream error",e)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);void 0!==n&&(this.log("replacing existing inbound steam %s",r),n.close().catch(e=>{this.log.error(e)})),this.log("create inbound stream %s",r);let i=new od(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,i),this.pipePeerReadStream(e,i.source).catch(e=>{this.log(e)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.add(n),this.score.addPeer(n);let i=function(e){for(let t of e.tuples())switch(t[0]){case eJ.ip4:case eJ.ip6:return(0,oI.xV)(t[0],t[1])}return null}(r);null!==i?this.score.addIP(n,i):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,"outbound"===t)}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);for(let e of(null!=r&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch(e=>{this.log.error(e)}),n?.close().catch(e=>{this.log.error(e)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t),this.topics.values()))e.delete(t);for(let[e,r]of this.mesh)r.delete(t)&&this.metrics?.onRemoveFromMesh(e,ej.Dc,1);for(let e of this.fanout.values())e.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===eX.started}getMeshPeers(e){let t=this.mesh.get(e);return null!=t?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(null!=t?Array.from(t):[]).map(e=>(0,nF.jE)(e))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await (0,tg.z)(t,async t=>{for await(let r of t)try{let t=r.subarray(),n=eU.decode(t,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos}}}});if(this.metrics?.onRpcRecv(n,t.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,n)}catch(e){this.metrics?.onRpcRecvError(),this.log(e)}else this.handleReceivedRpc(e,n).catch(e=>{this.metrics?.onRpcRecvError(),this.log(e)})}catch(e){this.metrics?.onRpcDataError(),this.log(e)}})}catch(t){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(t,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=null!=t.subscriptions?t.subscriptions.length:0,n=null!=t.messages?t.messages.length:0,i=0,s=0,o=0,a=0;if(null!=t.control&&(null!=t.control.ihave&&(i=t.control.ihave.length),null!=t.control.iwant&&(s=t.control.iwant.length),null!=t.control.graft&&(o=t.control.graft.length),null!=t.control.prune&&(a=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${s} graft ${o} prune ${a}`),null!=t.subscriptions&&t.subscriptions.length>0){let r=[];t.subscriptions.forEach(t=>{let n=t.topic,i=!0===t.subscribe;if(null!=n){if(null!=this.allowedTopics&&!this.allowedTopics.has(n))return;this.handleReceivedSubscription(e,n,i),r.push({topic:n,subscribe:i})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:r}})}for(let r of t.messages){if(null!=this.allowedTopics&&!this.allowedTopics.has(r.topic))continue;let t=this.handleReceivedMessage(e,r).catch(e=>{this.metrics?.onMsgRecvError(r.topic),this.log(e)});this.opts.awaitRpcMessageHandler&&await t}null!=t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);null==n&&(n=new Set,this.topics.set(t,n)),r?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case e$.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case e$.invalid:if(null!=r.msgIdStr){let n=r.msgIdStr;this.score.rejectMessage(e.toString(),n,t.topic,r.reason),this.gossipTracer.rejectMessage(n,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case e$.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new tQ.A("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new tQ.A("message",{detail:r.msg}))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=void 0!==r?this.fastMsgIdCache?.get(r):void 0;if(null!=n)return{code:e$.duplicate,msgIdStr:n};let i=await om(this.globalSignaturePolicy,t);if(!i.valid)return{code:e$.invalid,reason:eV.Error,error:i.error};let s=i.message;try{null!=this.dataTransform&&(s.data=this.dataTransform.inboundTransform(t.topic,s.data))}catch(e){return this.log("Invalid message, transform failed",e),{code:e$.invalid,reason:eV.Error,error:eH.TransformFailed}}let o=await this.msgIdFn(s),a=this.msgIdToStrFn(o);if(void 0!==r&&null!=this.fastMsgIdCache&&this.fastMsgIdCache.put(r,a)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(a))return{code:e$.duplicate,msgIdStr:a};this.seenCache.put(a);let l=this.topicValidators.get(t.topic);if(null!=l){let t;try{t=await l(e,s)}catch(r){let e=r.code;"ERR_TOPIC_VALIDATOR_IGNORE"===e&&(t=eM.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===e?eM.Reject:eM.Ignore}if(t!==eM.Accept)return{code:e$.invalid,reason:oe(t),msgIdStr:a}}return{code:e$.valid,messageId:{msgId:o,msgIdStr:a},msg:s}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map(e=>({topic:e,subscribe:r})),messages:[]})}async handleControlMessage(e,t){if(void 0===t)return;let r=null!=t.ihave?this.handleIHave(e,t.ihave):[],n=null!=t.iwant?this.handleIWant(e,t.iwant):[],i=null!=t.graft?await this.handleGraft(e,t.graft):[];if(null!=t.prune&&await this.handlePrune(e,t.prune),0===r.length&&0===n.length&&0===i.length)return;let s=this.sendRpc(e,oy(n,{iwant:r,prune:i})),o=r[0]?.messageIDs;null!=o&&(s?this.gossipTracer.addPromise(e,o):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),r=this.acceptFromWhitelist.get(e);if(null!=r&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(0===t.length)return[];let r=this.score.score(e);if(r10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:eW.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:eW.MaxIasked}),[];let s=new Map;if(t.forEach(({topicID:e,messageIDs:t})=>{if(null==e||null==t||!this.mesh.has(e))return;let r=0;t.forEach(e=>{let t=this.msgIdToStrFn(e);!this.seenCache.has(t)&&(s.set(t,e),r++)}),this.metrics?.onIhaveRcv(e,t.length,r)}),0===s.size)return[];let o=s.size;o+i>5e3&&(o=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",o,s.size,e);let a=Array.from(s.values());return ow(a),a=a.slice(0,o),this.iasked.set(e,i+o),[{messageIDs:a}]}handleIWant(e,t){if(0===t.length)return[];let r=this.score.score(e);if(r{t?.forEach(t=>{let r=this.msgIdToStrFn(t),o=this.mcache.getWithIWantCount(r,e);if(null==o){s++;return}if(i.set(o.msg.topic,1+(i.get(o.msg.topic)??0)),o.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,t);return}n.set(r,o.msg)})}),this.metrics?.onIwantRcv(i,s),0===n.size)?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),s=this.opts.doPX;return(t.forEach(({topicID:t})=>{if(null==t)return;let o=this.mesh.get(t);if(null==o){s=!1;return}if(o.has(e))return;if(this.direct.has(e)){this.log("GRAFT: ignoring request from direct peer %s",e),r.push(t),s=!1;return}let a=this.backoff.get(t)?.get(e);if("number"==typeof a&&i=this.opts.Dhi&&!this.outbound.get(e)){r.push(t),this.addBackoff(e,t);return}this.log("GRAFT: Add mesh link from %s in %s",e,t),this.score.graft(e,t),o.add(e),this.metrics?.onAddToMesh(t,ez.Subscribed,1)}),0===r.length)?[]:Promise.all(r.map(async t=>this.makePrune(e,t,s,!1)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:s}of t){if(null==n)continue;let t=this.mesh.get(n);if(null==t)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),t.has(e)&&(t.delete(e),this.metrics?.onRemoveFromMesh(n,ej.Prune,1)),"number"==typeof i&&i>0?this.doAddBackoff(e,n,1e3*i):this.addBackoff(e,n),null!=s&&s.length>0){if(r{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,eG.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!=0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((r,n)=>{r+1*this.opts.heartbeatInterval{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async e=>this.connect(e)))}async pxConnect(e){e.length>this.opts.prunePeers&&(ow(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async e=>{if(null==e.peerID)return;let r=(0,nF.cv)(e.peerID),n=r.toString();if(!this.peers.has(n)){if(null==e.signedPeerRecord){t.push(n);return}try{if(!await this.components.peerStore.consumePeerRecord(e.signedPeerRecord,r)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(n)}catch(e){this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),0!==t.length&&await Promise.all(t.map(async e=>this.connect(e)))}async connect(e){this.log("Initiating connection with %s",e);let t=(0,nF.jE)(e),r=await this.components.connectionManager.openConnection(t);for(let e of this.multicodecs)for(let n of this.components.registrar.getTopologies(e))n.onConnect?.(t,r)}subscribe(e){if(this.status.code!==eX.started)throw Error("Pubsub has not started");if(!this.subscriptions.has(e))for(let t of(this.subscriptions.add(e),this.peers.keys()))this.sendSubscriptions(t,[e],!0);this.join(e)}unsubscribe(e){if(this.status.code!==eX.started)throw Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!1);this.leave(e)}join(e){if(this.status.code!==eX.started)throw Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(null!=n&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(e=>{!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e))&&t.add(e)}),this.metrics?.onAddToMesh(e,ez.Fanout,t.size)),t.size!t.has(e)&&!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e))).forEach(e=>{t.add(e)}),this.metrics?.onAddToMesh(e,ez.Random,t.size-n)}this.mesh.set(e,t),t.forEach(t=>{this.log("JOIN: Add mesh link to %s in %s",t,e),this.sendGraft(t,e)})}leave(e){if(this.status.code!==eX.started)throw Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);null!=t&&(Promise.all(Array.from(t).map(async t=>{this.log("LEAVE: Remove mesh link to %s in %s",t,e),await this.sendPrune(t,e)})).catch(e=>{this.log("Error sending prunes to mesh peers",e)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,i=this.topics.get(e);null!=i&&(this.direct.forEach(e=>{i.has(e)&&t!==e&&!r?.has(e)&&n.add(e)}),this.floodsubPeers.forEach(e=>{i.has(e)&&t!==e&&!r?.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&n.add(e)}));let s=this.mesh.get(e);return null!=s&&s.size>0&&s.forEach(e=>{t===e||r?.has(e)||n.add(e)}),n}selectPeersToPublish(e){let t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(null!=n){if(this.opts.floodPublish)n.forEach(e=>{this.direct.has(e)?(t.add(e),r.direct++):this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),r.floodsub++)});else{this.direct.forEach(e=>{n.has(e)&&(t.add(e),r.direct++)}),this.floodsubPeers.forEach(e=>{n.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),r.floodsub++)});let i=this.mesh.get(e);if(null!=i&&i.size>0)i.forEach(e=>{t.add(e),r.mesh++});else{let n=this.fanout.get(e);if(null!=n&&n.size>0)n.forEach(e=>{t.add(e),r.fanout++});else{let n=this.getRandomGossipPeers(e,this.opts.D,e=>this.score.score(e)>=this.opts.scoreThresholds.publishThreshold);n.size>0&&(this.fanout.set(e,n),n.forEach(e=>{t.add(e),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){null!=r&&this.score.deliverMessage(r,e,t.topic);let i=this.selectPeersToForward(t.topic,r,n);i.forEach(e=>{this.sendRpc(e,oy([t]))}),this.metrics?.onForwardMsg(t.topic,i.size)}async publish(e,t,r){let n=Date.now(),i=null!=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(null==this.publishConfig)throw Error("PublishError.Uninitialized");let{raw:s,msg:o}=await og(this.publishConfig,e,t,i),a=await this.msgIdFn(o),l=this.msgIdToStrFn(a),c=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(c)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:u,tosendCount:h}=this.selectPeersToPublish(e),d=this.opts.emitSelf&&this.subscriptions.has(e),p=r?.allowPublishToZeroPeers??this.opts.allowPublishToZeroPeers;if(0===u.size&&!p&&!d)throw Error("PublishError.InsufficientPeers");this.seenCache.put(l),this.mcache.put({msgId:a,msgIdStr:l},s,!0),this.publishedMessageIds.put(l);let f=r?.batchPublish??this.opts.batchPublish,g=oy([s]);if(f)this.sendRpcInBatch(u,g);else for(let e of u)this.sendRpc(e,g)||u.delete(e);let m=Date.now()-n;return this.metrics?.onPublishMsg(e,h,u.size,null!=s.data?s.data.length:0,m),d&&(u.add(this.components.peerId.toString()),super.dispatchEvent(new tQ.A("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:o}})),super.dispatchEvent(new tQ.A("message",{detail:o}))),{recipients:Array.from(u.values()).map(e=>(0,nF.jE)(e))}}sendRpcInBatch(e,t){let r=eU.encode(t),n=tf.c.single(r);for(let i of e){let s=this.streamsOutbound.get(i);if(null==s){this.log(`Cannot send RPC to ${i} as there is no open stream to it available`),e.delete(i);continue}try{s.pushPrefixed(n)}catch(t){e.delete(i),this.log.error(`Cannot send rpc to ${i}`,t)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===eM.Accept){if(null!=(n=this.mcache.validate(e))){let{message:r,originatingPeers:i}=n;this.score.deliverMessage(t,e,r.topic),this.forwardMessage(e,n.message,t,i)}}else if(null!=(n=this.mcache.remove(e))){let i=oe(r),{message:s,originatingPeers:o}=n;for(let r of(this.score.rejectMessage(t,e,s.topic,i),o))this.score.rejectMessage(r,e,s.topic,i)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let r=oy([],{graft:[{topicID:t}]});this.sendRpc(e,r)}async sendPrune(e,t){let r=oy([],{prune:[await this.makePrune(e,t,this.opts.doPX,!0)]});this.sendRpc(e,r)}sendRpc(e,t){let r=this.streamsOutbound.get(e);if(null==r)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);null!=n&&(this.piggybackControl(e,t,n),this.control.delete(e));let i=this.gossip.get(e);null!=i&&(this.piggybackGossip(e,t,i),this.gossip.delete(e));let s=eU.encode(t);try{r.push(s)}catch(t){return this.log.error(`Cannot send rpc to ${e}`,t),null!=n&&this.control.set(e,n),null!=i&&this.gossip.set(e,i),!1}return this.metrics?.onRpcSent(t,s.length),!0}piggybackControl(e,t,r){let n=ob(t);for(let t of r.graft)null!=t.topicID&&this.mesh.get(t.topicID)?.has(e)&&n.control.graft.push(t);for(let t of r.prune)null==t.topicID||this.mesh.get(t.topicID)?.has(e)||n.control.prune.push(t)}piggybackGossip(e,t,r){ob(t).control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX;for(let[i,s]of e){let e=s.map(e=>({topicID:e})),o=[],a=t.get(i);null!=a&&(o=await Promise.all(a.map(async e=>this.makePrune(i,e,n&&!r.get(i),!1))),t.delete(i)),this.sendRpc(i,oy([],{graft:e,prune:o}))}for(let[e,i]of t){let t=await Promise.all(i.map(async t=>this.makePrune(e,t,n&&!r.get(e),!1)));this.sendRpc(e,oy([],{prune:t}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(0===r.length||(ow(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),0===t.size))return;let n=this.opts.Dlazy,i=.25*t.size,s=t;i>n&&(n=i),n>s.size?n=s.size:s=ow(Array.from(s)).slice(0,n),s.forEach(t=>{let n=r;r.length>5e3&&(n=ow(n.slice()).slice(0,5e3)),this.pushGossip(t,{topicID:e,messageIDs:n})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,oy([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=oy([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===s5)return{topicID:t,peers:[]};let i=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,s=i/1e3;if(this.doAddBackoff(e,t,i),!r)return{topicID:t,peers:[],backoff:s};let o=this.getRandomGossipPeers(t,this.opts.prunePeers,t=>t!==e&&this.score.score(t)>=0);return{topicID:t,peers:await Promise.all(Array.from(o).map(async e=>{let t;let r=(0,nF.jE)(e);try{t=await this.components.peerStore.get(r)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{peerID:r.toBytes(),signedPeerRecord:t?.peerRecordEnvelope}})),backoff:s}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(e=>{this.log("Error running heartbeat",e)}).finally(()=>{if(null!=e&&e(),this.status.code===eX.started){clearTimeout(this.status.heartbeatTimeout);let e=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;e<.25*this.opts.heartbeatInterval&&(e+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,e)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:s}=this.opts;this.heartbeatTicks++;let o=new Map,a=e=>{let t=o.get(e);return void 0===t&&(t=this.score.score(e),o.set(e,t)),t},l=new Map,c=new Map,u=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks==0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let h=new Map;this.mesh.forEach((s,o)=>{let d=this.topics.get(o),p=new Set,f=new Set;if(h.set(o,f),null!=d){let e=ow(Array.from(d)),t=this.backoff.get(o);for(let r of e){let e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!s.has(r)&&!this.direct.has(r)){let e=a(r);(null==t||!t.has(r))&&e>=0&&p.add(r),e>=this.opts.scoreThresholds.gossipThreshold&&f.add(r)}}}let g=(e,t)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",e,o),this.addBackoff(e,o),s.delete(e),a(e)>=this.opts.scoreThresholds.gossipThreshold&&f.add(e),this.metrics?.onRemoveFromMesh(o,t,1);let r=c.get(e);null==r?c.set(e,[o]):r.push(o)},m=(e,t)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",e,o),this.score.graft(e,o),s.add(e),f.delete(e),this.metrics?.onAddToMesh(o,t,1);let r=l.get(e);null==r?l.set(e,[o]):r.push(o)};if(s.forEach(e=>{let t=a(e);t<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",e,t,o),g(e,ej.BadScore),u.set(e,!0))}),s.size!0).forEach(e=>{m(e,ez.NotEnough)}),s.size>r){let t=Array.from(s);t.sort((e,t)=>a(t)-a(e));let r=0;if((t=t.slice(0,n).concat(ow(t.slice(n)))).slice(0,e).forEach(e=>{this.outbound.get(e)&&r++}),r{let r=t[e];for(let r=e;r>0;r--)t[r]=t[r-1];t[0]=r};if(r>0){let i=r;for(let r=1;r0;r++)this.outbound.get(t[r])&&(n(r),i--)}let i=e-r;for(let r=e;r0;r++)this.outbound.get(t[r])&&(n(r),i--)}t.slice(e).forEach(e=>{g(e,ej.Excess)})}if(s.size>=t){let e=0;s.forEach(t=>{this.outbound.get(t)&&e++}),e!0===this.outbound.get(e)).forEach(e=>{m(e,ez.Outbound)})}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks==0&&s.size>1){let e=Array.from(s).sort((e,t)=>a(e)-a(t)),t=a(e[Math.floor(s.size/2)]);if(ta(e)>t))this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",e,o),m(e,ez.Opportunistic)}});let d=Date.now();this.fanoutLastpub.forEach((e,t)=>{e+s{let n=this.topics.get(r);t.forEach(e=>{(!n?.has(e)||a(e)=this.opts.scoreThresholds.publishThreshold&&s.push(e),t>=this.opts.scoreThresholds.gossipThreshold&&o.add(e)}}if(t.size{t.add(e),o?.delete(e)})}}),this.emitGossip(h),await this.sendGraftPrune(l,c,u),this.flush(),this.mcache.shift(),this.dispatchEvent(new tQ.A("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(null==n)return new Set;let i=[];return n.forEach(e=>{let t=this.streamsOutbound.get(e);null!=t&&this.multicodecs.includes(t.protocol)&&r(e)&&i.push(e)}),i=ow(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();for(let n of(e.connectedPeersBackoffSec.reset(),this.backoff.values()))for(let[i,s]of(t+=n.size,n.entries()))this.peers.has(i)&&e.connectedPeersBackoffSec.observe(Math.max(0,s-r)/1e3);for(let[r,n]of(e.cacheSize.set({cache:"backoff"},t),this.topics))e.topicPeersCount.set({topicStr:r},n.size);for(let[t,r]of this.mesh)e.meshPeerCounts.set({topicStr:t},r.size);let n=[],i=new Map;for(let t of(e.behaviourPenalty.reset(),this.peers.keys())){let r=this.score.score(t);n.push(r),i.set(t,r),e.behaviourPenalty.observe(this.score.peerStats.get(t)?.behaviourPenalty??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let s=function(e,t,r,n,i){let s={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of e){let e=t.get(o);if(null!=e){let t=function(e,t,r,n,i){let s,o=0,a=new Map;if(Object.entries(t.topics).forEach(([e,t])=>{let n=i.get(e)??"unknown",s=r.topics[e];if(void 0===s)return;let l=a.get(n);null==l&&(l={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},a.set(n,l));let c=0,u=0,h=0,d=0,p=0;t.inMesh&&(c+=Math.max(t.meshTime/s.timeInMeshQuantum,s.timeInMeshCap)*s.timeInMeshWeight);let f=t.firstMessageDeliveries;if(f>s.firstMessageDeliveriesCap&&(f=s.firstMessageDeliveriesCap),u+=f*s.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries0&&o>r.topicScoreCap){o=r.topicScoreCap;let e=r.topicScoreCap/o;for(let t of a.values())t.p1w*=e,t.p2w*=e,t.p3w*=e,t.p3bw*=e,t.p4w*=e}let l=0,c=0;return s=0+r.appSpecificScore(e)*r.appSpecificWeight,t.knownIPs.forEach(e=>{if(r.IPColocationFactorWhitelist.has(e))return;let t=n.get(e),i=null!=t?t.size:0;if(i>r.IPColocationFactorThreshold){let e=i-r.IPColocationFactorThreshold;l+=e*e*r.IPColocationFactorWeight}}),c+=t.behaviourPenalty*t.behaviourPenalty*r.behaviourPenaltyWeight,o+=s+l+c,{byTopic:a,p5w:s,p6w:l,p7w:c,score:o}}(o,e,r,n,i);for(let[e,r]of t.byTopic){let t=s.byTopic.get(e);null==t&&(t={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},s.byTopic.set(e,t)),t.p1w.push(r.p1w),t.p2w.push(r.p2w),t.p3w.push(r.p3w),t.p3bw.push(r.p3bw),t.p4w.push(r.p4w)}s.p5w.push(t.p5w),s.p6w.push(t.p6w),s.p7w.push(t.p7w),s.score.push(t.score)}else s.p5w.push(0),s.p6w.push(0),s.p7w.push(0),s.score.push(0)}return s}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(s)}}let oR=["/vac/waku/relay/2.0.0"],ok=new ts.Yd("relay");function oP(e,t){let r=performance.now();ok.info(`validating message from ${e} received on ${t.topic}`);let n=eM.Accept;try{let e=ti.u.H.decode(t.data);e.contentTopic&&e.contentTopic.length&&e.payload&&e.payload.length||(n=eM.Reject)}catch(e){n=eM.Reject}let i=performance.now()-r;return i>100?ok.warn(`message validation took ${i}ms for peer ${e} on topic ${t.topic}. This should be less than 100ms.`):ok.info(`message validation took ${i}ms for peer ${e} on topic ${t.topic}`),n}class oD{pubsubTopic;proto;payload=new Uint8Array;rateLimitProof;timestamp;meta;ephemeral;constructor(e,t){this.pubsubTopic=e,this.proto=t}get contentTopic(){return this.proto.contentTopic}}class oB{pubsubTopic=tC.nf;contentTopic="";fromWireToProtoObj(e){return Promise.resolve({contentTopic:ti.aF.decode(e).contentTopic,payload:new Uint8Array,rateLimitProof:void 0,timestamp:void 0,meta:void 0,version:void 0,ephemeral:void 0})}async fromProtoObj(e,t){return new oD(e,t)}}let oN=new ts.Yd("relay");class oL{pubsubTopics;defaultDecoder;static multicodec="/vac/waku/relay/2.0.0";gossipSub;observers;constructor(e,t){if(!this.isRelayPubsub(e.services.pubsub))throw Error(`Failed to initialize Relay. libp2p.pubsub does not support ${oL.multicodec}`);this.gossipSub=e.services.pubsub,this.pubsubTopics=new Set(t),this.gossipSub.isStarted()&&this.subscribeToAllTopics(),this.observers=new Map,this.defaultDecoder=new oB}async start(){if(this.gossipSub.isStarted())throw Error("GossipSub already started.");await this.gossipSub.start(),this.subscribeToAllTopics()}async send(e,t){let r=[],{pubsubTopic:n}=e;if(!this.pubsubTopics.has(n))return oN.error("Failed to send waku relay: topic not configured"),{successes:r,failures:[{error:tC.K1.TOPIC_NOT_CONFIGURED}]};let i=await e.toWire(t);if(!i)return oN.error("Failed to encode message, aborting publish"),{successes:r,failures:[{error:tC.K1.ENCODE_FAILED}]};if(!(0,ts.qc)(i))return oN.error("Failed to send waku relay: message is bigger that 1MB"),{successes:r,failures:[{error:tC.K1.SIZE_TOO_BIG}]};let{recipients:s}=await this.gossipSub.publish(n,i);return{successes:s}}subscribe(e,t){let r=[];for(let n of Array.isArray(e)?e:[e]){let{pubsubTopic:e}=n,i=this.observers.get(e)??new Map,s={pubsubTopic:e,decoder:n,callback:t};(0,ts.IC)(i,n.contentTopic,s),this.observers.set(e,i),r.push([e,s])}return()=>{this.removeObservers(r)}}removeObservers(e){for(let[t,r]of e){let e=this.observers.get(t);if(!e)continue;let n=r.decoder.contentTopic,i=e.get(n);i&&(i.delete(r),e.set(n,i),this.observers.set(t,e))}}toSubscriptionIterator(e){return(0,ts.B2)(this,e)}getActiveSubscriptions(){let e=new Map;for(let t of this.pubsubTopics)e.set(t,Array.from(this.observers.keys()));return e}getMeshPeers(e=tC.nf){return this.gossipSub.getMeshPeers(e)}subscribeToAllTopics(){for(let e of this.pubsubTopics)this.gossipSubSubscribe(e)}async processIncomingMessage(e,t){let r=await this.defaultDecoder.fromWireToProtoObj(t);if(!r||!r.contentTopic){oN.warn("Message does not have a content topic, skipping");return}let n=this.observers.get(e);if(!n)return;let i=n.get(r.contentTopic);i&&await Promise.all(Array.from(i).map(({decoder:n,callback:i})=>(async()=>{try{let s=await n.fromWireToProtoObj(t);if(!s){oN.error("Internal error: message previously decoded failed on 2nd pass.");return}let o=await n.fromProtoObj(e,s);o?await i(o):oN.error("Failed to decode messages on",r.contentTopic)}catch(e){oN.error("Error while decoding message:",e)}})()))}gossipSubSubscribe(e){this.gossipSub.addEventListener("gossipsub:message",t=>{t.detail.msg.topic===e&&this.processIncomingMessage(t.detail.msg.topic,t.detail.msg.data).catch(e=>oN.error("Failed to process incoming message",e))}),this.gossipSub.topicValidators.set(e,oP),this.gossipSub.subscribe(e)}isRelayPubsub(e){return e?.multicodecs?.includes(oL.multicodec)??!1}}let ox=Symbol.for("@libp2p/content-routing"),oO=Symbol.for("@libp2p/peer-routing");var oM=r(55022),oU=r(60522);function oF(){return{forComponent:e=>{let t;return t=function(e){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`),oM.enabled(`${e}:trace`)&&null!=oM.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(t=oM(`${e}:trace`)),Object.assign(oM(e),{error:oM(`${e}:error`),trace:t})}}}function oK(e,t){let r={[Symbol.iterator]:()=>r,next:()=>{let r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}oM.formatters.b=e=>null==e?"undefined":r1.base58btc.baseEncode(e),oM.formatters.t=e=>null==e?"undefined":oU.base32.baseEncode(e),oM.formatters.m=e=>null==e?"undefined":nt.base64.baseEncode(e),oM.formatters.p=e=>null==e?"undefined":e.toString(),oM.formatters.c=e=>null==e?"undefined":e.toString(),oM.formatters.k=e=>null==e?"undefined":e.toString(),oM.formatters.a=e=>null==e?"undefined":e.toString();class oV{set;constructor(e){if(this.set=new Set,null!=e)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 oK(this.set.entries(),e=>{let t=(0,nF.jE)(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let r=(0,nF.jE)(t);e(r,r,this)})}has(e){return this.set.has(e.toString())}values(){return oK(this.set.values(),e=>(0,nF.jE)(e))}intersection(e){let t=new oV;for(let r of e)this.has(r)&&t.add(r);return t}difference(e){let t=new oV;for(let r of this)e.has(r)||t.add(r);return t}union(e){let t=new oV;for(let r of e)t.add(r);for(let e of this)t.add(e);return t}}var oH=r(90678);class o${map;constructor(e){if(this.map=new Map,null!=e)for(let[t,r]of e.entries())this.map.set(t.toString(),r)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return oK(this.map.entries(),e=>[(0,nF.jE)(e[0]),e[1]])}forEach(e){this.map.forEach((t,r)=>{e(t,(0,nF.jE)(r),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 oK(this.map.keys(),e=>(0,nF.jE)(e))}values(){return this.map.values()}get size(){return this.map.size}}var oq=r(36393);class oz{#o=[];enqueue(e,t){let r={priority:(t={priority:0,...t}).priority,run:e};if(this.size&&this.#o[this.size-1].priority>=t.priority){this.#o.push(r);return}let n=function(e,t,r){let n=0,i=e.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;0>=r(e[o],t)?(n=++o,i-=s+1):i=s}return n}(this.#o,r,(e,t)=>t.priority-e.priority);this.#o.splice(n,0,r)}dequeue(){let e=this.#o.shift();return e?.run}filter(e){return this.#o.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#o.length}}class oj extends oq.v{#a;#l;#c=0;#u;#h;#d=0;#p;#f;#o;#g;#m=0;#y;#b;#v;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:oz,...e}).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#a=e.carryoverConcurrencyCount,this.#l=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#u=e.intervalCap,this.#h=e.interval,this.#o=new e.queueClass,this.#g=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#v=!0===e.throwOnTimeout,this.#b=!1===e.autoStart}get #w(){return this.#l||this.#c{this.#I()},t)),!0;this.#c=this.#a?this.#m:0}return!1}#A(){if(0===this.#o.size)return this.#p&&clearInterval(this.#p),this.#p=void 0,this.emit("empty"),0===this.#m&&this.emit("idle"),!1;if(!this.#b){let e=!this.#C;if(this.#w&&this.#E){let t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#T(),!0)}}return!1}#T(){this.#l||void 0!==this.#p||(this.#p=setInterval(()=>{this.#_()},this.#h),this.#d=Date.now()+this.#h)}#_(){0===this.#c&&0===this.#m&&this.#p&&(clearInterval(this.#p),this.#p=void 0),this.#c=this.#a?this.#m:0,this.#R()}#R(){for(;this.#A(););}get concurrency(){return this.#y}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#R()}async #k(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#v,...t},new Promise((r,n)=>{this.#o.enqueue(async()=>{this.#m++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=tH(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#k(t.signal)]));let i=await n;r(i),this.emit("completed",i)}catch(e){if(e instanceof tU&&!t.throwOnTimeout){r();return}n(e),this.emit("error",e)}finally{this.#S()}},t),this.emit("add"),this.#A()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#b&&(this.#b=!1,this.#R()),this}pause(){this.#b=!0}clear(){this.#o=new this.#g}async onEmpty(){0!==this.#o.size&&await this.#P("empty")}async onSizeLessThan(e){this.#o.sizethis.#o.size{let n=()=>{(!t||t())&&(this.off(e,n),r())};this.on(e,n)})}get size(){return this.#o.size}sizeBy(e){return this.#o.filter(e).length}get pending(){return this.#m}get isPaused(){return this.#b}}let oG={},oW=e=>{e.addEventListener("message",t=>{oW.dispatchEvent("message",e,t)}),null!=e.port&&e.port.addEventListener("message",t=>{oW.dispatchEvent("message",e,t)})};oW.addEventListener=(e,t)=>{null==oG[e]&&(oG[e]=[]),oG[e].push(t)},oW.removeEventListener=(e,t)=>{null!=oG[e]&&(oG[e]=oG[e].filter(e=>e===t))},oW.dispatchEvent=function(e,t,r){null!=oG[e]&&oG[e].forEach(e=>e(t,r))};let oY="lock:worker:request-read",oQ="lock:worker:release-read",oJ="lock:master:grant-read",oX="lock:worker:request-write",oZ="lock:worker:release-write",o0="lock:master:grant-write",o1=(e=21)=>Math.random().toString().substring(2),o2=(e,t,r,n,i)=>(s,o)=>{if(o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(e=>{let t=r=>{if(null==r||null==r.data)return;let i={type:r.data.type,name:r.data.name,identifier:r.data.identifier};i.type===n&&i.identifier===a.identifier&&(s.removeEventListener("message",t),e())};s.addEventListener("message",t)})}}}))},o3=(e,t,r,n)=>async()=>{let i=o1();return globalThis.postMessage({type:t,identifier:i,name:e}),new Promise(t=>{let s=o=>{if(null==o||null==o.data)return;let a={type:o.data.type,identifier:o.data.identifier};a.type===r&&a.identifier===i&&(globalThis.removeEventListener("message",s),t(()=>{globalThis.postMessage({type:n,identifier:i,name:e})}))};globalThis.addEventListener("message",s)})},o4={singleProcess:!1};var o6=e=>{if(e=Object.assign({},o4,e),globalThis.document||e.singleProcess){let e=new EventTarget;return oW.addEventListener("message",o2(e,"requestReadLock",oY,oQ,oJ)),oW.addEventListener("message",o2(e,"requestWriteLock",oX,oZ,o0)),e}return{isWorker:!0,readLock:e=>o3(e,oY,oJ,oQ),writeLock:e=>o3(e,oX,o0,oZ)}};let o5={};async function o8(e,t){let r;let n=new Promise(e=>{r=e});return e.add(async()=>tH((async()=>{await new Promise(e=>{r(()=>{e()})})})(),{milliseconds:t.timeout})),n}let o9=(e,t)=>{let r;if(!0===i.isWorker)return{readLock:i.readLock(e,t),writeLock:i.writeLock(e,t)};let n=new oj({concurrency:1});return{async readLock(){if(null!=r)return o8(r,t);let e=r=new oj({concurrency:t.concurrency,autoStart:!1}),i=o8(r,t);return n.add(async()=>{e.start(),await e.onIdle().then(()=>{r===e&&(r=null)})}),i},writeLock:async()=>(r=null,o8(n,t))}},o7={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1},ae={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};function at(e,t){let r=eZ.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=(0,nF.vL)({...e,publicKey:e.publicKey}));let n=new Map,i=BigInt(Date.now());for(let[e,t]of r.tags.entries())null!=t.expiry&&t.expiry({multiaddr:(0,n0.HM)(e),isCertified:t??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}(ep=(ed=eZ||(eZ={})).Peer$metadataEntry||(ed.Peer$metadataEntry={})).codec=()=>(null==A&&(A=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={key:"",value:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r})),A),ep.encode=e=>(0,ns.LE)(e,ep.codec()),ep.decode=e=>(0,ns.C6)(e,ep.codec()),(ef=ed.Peer$tagsEntry||(ed.Peer$tagsEntry={})).codec=()=>(null==I&&(I=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),e1.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={key:""},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=e1.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r})),I),ef.encode=e=>(0,ns.LE)(e,ef.codec()),ef.decode=e=>(0,ns.C6)(e,ef.codec()),ed.codec=()=>(null==S&&(S=(0,ns.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.addresses)for(let r of e.addresses)t.uint32(10),e0.codec().encode(r,t);if(null!=e.protocols)for(let r of e.protocols)t.uint32(18),t.string(r);if(null!=e.publicKey&&(t.uint32(34),t.bytes(e.publicKey)),null!=e.peerRecordEnvelope&&(t.uint32(42),t.bytes(e.peerRecordEnvelope)),null!=e.metadata&&0!==e.metadata.size)for(let[r,n]of e.metadata.entries())t.uint32(50),ed.Peer$metadataEntry.codec().encode({key:r,value:n},t);if(null!=e.tags&&0!==e.tags.size)for(let[r,n]of e.tags.entries())t.uint32(58),ed.Peer$tagsEntry.codec().encode({key:r,value:n},t);!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={addresses:[],protocols:[],metadata:new Map,tags:new Map},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.addresses.push(e0.codec().decode(e,e.uint32()));break;case 2:r.protocols.push(e.string());break;case 4:r.publicKey=e.bytes();break;case 5:r.peerRecordEnvelope=e.bytes();break;case 6:{let t=ed.Peer$metadataEntry.codec().decode(e,e.uint32());r.metadata.set(t.key,t.value);break}case 7:{let t=ed.Peer$tagsEntry.codec().decode(e,e.uint32());r.tags.set(t.key,t.value);break}default:e.skipType(7&t)}}return r})),S),ed.encode=e=>(0,ns.LE)(e,ed.codec()),ed.decode=e=>(0,ns.C6)(e,ed.codec()),(eg=e0||(e0={})).codec=()=>(null==_&&(_=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;default:e.skipType(7&t)}}return r})),_),eg.encode=e=>(0,ns.LE)(e,eg.codec()),eg.decode=e=>(0,ns.C6)(e,eg.codec()),(em=e1||(e1={})).codec=()=>(null==T&&(T=(0,ns.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r})),T),em.encode=e=>(0,ns.LE)(e,em.codec()),em.decode=e=>(0,ns.C6)(e,em.codec());var ar=r(25906);let an=new TextEncoder().encode("/"),ai=an[0];class as{_buf;constructor(e,t){if("string"==typeof e)this._buf=(0,r0.m)(e);else if(e instanceof Uint8Array)this._buf=e;else throw Error("Invalid key, should be String of Uint8Array");if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==ai)throw Error("Invalid key")}toString(e="utf8"){return(0,r5.B)(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new as(e.join("/"))}static random(){return new as(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new as(e):"function"==typeof e.uint8Array?new as(e.uint8Array()):null}clean(){if((null==this._buf||0===this._buf.byteLength)&&(this._buf=an),this._buf[0]!==ai){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ai,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ai;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),r=e.list();for(let e=0;ei)return!1}return t.lengthe.namespaces()))])}}let ao="/peers/";function aa(e){if(!(0,ar.I)(e)||null==e.type)throw new rX.sv("Invalid PeerId",ae.ERR_INVALID_PARAMETERS);let t=e.toCID().toString();return new as(`${ao}${t}`)}async function al(e,t,r){let n=new Map;for(let i of r){if(null==i)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=(0,n0.HM)(i.multiaddr)),!(0,n0.h2)(i.multiaddr))throw new rX.sv("Multiaddr was invalid",ae.ERR_INVALID_PARAMETERS);if(!await t(e,i.multiaddr))continue;let r=i.isCertified??!1,s=i.multiaddr.toString(),o=n.get(s);null!=o?i.isCertified=o.isCertified||r:n.set(s,{multiaddr:i.multiaddr,isCertified:r})}return[...n.values()].sort((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString())).map(({isCertified:e,multiaddr:t})=>({isCertified:e,multiaddr:t.bytes}))}async function ac(e,t,r,n){if(null==t)throw new rX.sv("Invalid PeerData",ae.ERR_INVALID_PARAMETERS);if(null!=t.publicKey&&null!=e.publicKey&&!(0,r4.f)(t.publicKey,e.publicKey))throw new rX.sv("publicKey bytes do not match peer id publicKey bytes",ae.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(null!=i&&!e.equals(i.id))throw new rX.sv("peer id did not match existing peer id",ae.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,l=i?.tags??new Map,c=i?.peerRecordEnvelope;if("patch"===r&&((null!=t.multiaddrs||null!=t.addresses)&&(s=[],null!=t.multiaddrs&&s.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&s.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata&&(a=au(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:ah})),null!=t.tags&&(l=au(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:ad,map:ap})),null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&s.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&s.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...t.protocols])),null!=t.metadata){for(let[e,r]of t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata))null==r?a.delete(e):a.set(e,r);a=au([...a.entries()],{validate:ah})}if(null!=t.tags){let e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(let[t,n]of e)null==n?r.delete(t):r.set(t,n);l=au([...r.entries()],{validate:ad,map:ap})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}let u={addresses:await al(e,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((e,t)=>e.localeCompare(t)),metadata:a,tags:l,publicKey:i?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:c};return"RSA"!==e.type&&delete u.publicKey,u}function au(e,t){let r=new Map;for(let[r,n]of e)null!=n&&t.validate(r,n);for(let[n,i]of e.sort(([e],[t])=>e.localeCompare(t)))null!=i&&r.set(n,t.map?.(n,i)??i);return r}function ah(e,t){if("string"!=typeof e)throw new rX.sv("Metadata key must be a string",ae.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new rX.sv("Metadata value must be a Uint8Array",ae.ERR_INVALID_PARAMETERS)}function ad(e,t){if("string"!=typeof e)throw new rX.sv("Tag name must be a string",ae.ERR_INVALID_PARAMETERS);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new rX.sv("Tag value must be an integer",ae.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new rX.sv("Tag value must be between 0-100",ae.ERR_INVALID_PARAMETERS)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new rX.sv("Tag ttl must be an integer",ae.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new rX.sv("Tag ttl must be between greater than 0",ae.ERR_INVALID_PARAMETERS)}}function ap(e,t){let r;return null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function af(e,t,r){let n=e.toString().split("/")[2],i=oU.base32.decode(n),s=(0,nF.cv)(i),o=r.get(s);if(null!=o)return o;let a=at(s,t);return r.set(s,a),a}class ag{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){let t=Object.assign({},o7,e);return null==i&&!0!==(i=o6(t)).isWorker&&(i.addEventListener("requestReadLock",e=>{null!=o5[e.data.name]&&o5[e.data.name].readLock().then(async t=>e.data.handler().finally(()=>{t()}))}),i.addEventListener("requestWriteLock",async e=>{null!=o5[e.data.name]&&o5[e.data.name].writeLock().then(async t=>e.data.handler().finally(()=>{t()}))})),null==o5[t.name]&&(o5[t.name]=o9(t.name,t)),o5[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(aa(e))}async delete(e){if(this.peerId.equals(e))throw new rX.sv("Cannot delete self peer",ae.ERR_INVALID_PARAMETERS);await this.datastore.delete(aa(e))}async load(e){let t=await this.datastore.get(aa(e));return at(e,t)}async save(e,t){let{existingBuf:r,existingPeer:n}=await this.#D(e),i=await ac(e,t,"patch",{addressFilter:this.addressFilter});return this.#B(e,i,r,n)}async patch(e,t){let{existingBuf:r,existingPeer:n}=await this.#D(e),i=await ac(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#B(e,i,r,n)}async merge(e,t){let{existingBuf:r,existingPeer:n}=await this.#D(e),i=await ac(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#B(e,i,r,n)}async *all(e){var t;let r=new o$;for await(let{key:n,value:i}of this.datastore.query(null==(t=e??{})?{}:{prefix:ao,filters:(t.filters??[]).map(e=>({key:t,value:n})=>e(af(t,n,r))),orders:(t.orders??[]).map(e=>(t,n)=>e(af(t.key,t.value,r),af(n.key,n.value,r)))})){let e=af(n,i,r);e.id.equals(this.peerId)||(yield e)}}async #D(e){try{let t=await this.datastore.get(aa(e)),r=at(e,t);return{existingBuf:t,existingPeer:r}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async #B(e,t,r,n){let i=eZ.encode(t);return null!=r&&(0,r4.f)(i,r)?{peer:at(e,i),previous:n,updated:!1}:(await this.datastore.put(aa(e),i),{peer:at(e,i),previous:n,updated:!0})}}class am{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 ag(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let r of this.store.all(t))e(r)}finally{this.log.trace("forEach release read lock"),r()}}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 (0,tp.Z)(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 r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let r=await this.store.save(e,t);return this.#N(e,r),r.peer}finally{this.log.trace("save release write lock"),r()}}async patch(e,t){this.log.trace("patch await write lock");let r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let r=await this.store.patch(e,t);return this.#N(e,r),r.peer}finally{this.log.trace("patch release write lock"),r()}}async merge(e,t){this.log.trace("merge await write lock");let r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let r=await this.store.merge(e,t);return this.#N(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){let r;let n=await iD.openAndCertify(e,iR.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 i=iR.createFromProtobuf(n.payload);try{r=await this.get(n.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(r?.peerRecordEnvelope!=null){let e=await iD.createFromProtobuf(r.peerRecordEnvelope),t=iR.createFromProtobuf(e.payload);if(t.seqNumber>=i.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))}),!0}#N(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}var ay=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(let t of e);})();for(let t of e);},ab=function(e){let[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:e=>{n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}},av=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(let n of e)await t(n,r++)&&(yield n)}();let n=ab(e),{value:i,done:s}=n.next();if(!0===s)return function*(){}();let o=t(i,r++);return"function"==typeof o.then?async function*(){for await(let e of(await o&&(yield i),n))await t(e,r++)&&(yield e)}():function*(){for(let e of(!0===o&&(yield i),n))t(e,r++)&&(yield e)}()},aw=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=await (0,tp.Z)(e);yield*r.sort(t)}():function*(){let r=(0,tp.Z)(e);yield*r.sort(t)}()},aE=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1)){for await(let n of e)if(yield n,++r===t)return}}():function*(){let r=0;if(!(t<1)){for(let n of e)if(yield n,++r===t)return}}()};class aS{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async *putMany(e,t={}){for await(let{key:r,value:n}of e)await this.put(r,n,t),yield r}async *getMany(e,t={}){for await(let r of e)yield{key:r,value:await this.get(r,t)}}async *deleteMany(e,t={}){for await(let r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await ay(this.putMany(e,r)),e=[],await ay(this.deleteMany(t,r)),t=[]}}}async *_all(e,t){throw Error("._all is not implemented")}async *_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){let t=e.prefix;r=av(r,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>av(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>aw(e,t),r)),null!=e.offset){let t=0,n=e.offset;r=av(r,()=>t++>=n)}return null!=e.limit&&(r=aE(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){let t=e.prefix;r=av(r,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>av(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>aw(e,t),r)),null!=e.offset){let t=e.offset,n=0;r=av(r,()=>n++>=t)}return null!=e.limit&&(r=aE(r,e.limit)),r}}var aA=r(15862);class aI extends aS{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(null==t){var r;throw aA(r=r??Error("Not Found"),"ERR_NOT_FOUND")}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 as(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new as(e)}}let a_=e=>e;function aT(e,t){let r=e.getPeerId();return null!=r&&(0,nF.jE)(r).equals(t)&&(e=e.decapsulate((0,n0.HM)(`/p2p/${t.toString()}`))),e}class aC{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){var r;let n;let{listen:i=[],announce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=i.map(e=>e.toString()),this.announce=new Set(s.map(e=>e.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??a_,this._updatePeerStoreAddresses=(r=this._updatePeerStoreAddresses.bind(this),function(){clearTimeout(n),n=setTimeout(function(){n=void 0,r()},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(([e,t])=>t.confident).map(([e])=>(0,n0.HM)(e))).map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(e=>(0,n0.HM)(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>(0,n0.HM)(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>(0,n0.HM)(e))}addObservedAddr(e){let t=(e=aT(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){let t=(e=aT(e,this.components.peerId)).toString(),r=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),r||this._updatePeerStoreAddresses()}removeObservedAddr(e){let t=(e=aT(e,this.components.peerId)).toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(e=>e.toString());0===e.length&&(e=this.components.transportManager.getAddrs().map(e=>e.toString()));let t=new Set(e=e.concat(Array.from(this.observed).filter(([e,t])=>t.confident).map(([e])=>e)));return this.announceFilter(Array.from(t).map(e=>(0,n0.HM)(e))).map(e=>e.protos().pop()?.path===!0||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`))}}class aR{components={};_started=!1;constructor(e={}){for(let[t,r]of(this.components={},Object.entries(e)))this.components[t]=r;null==this.components.logger&&(this.components.logger=oF())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>null!=e&&"function"==typeof e.start&&"function"==typeof e.stop).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")}}let ak=["metrics","connectionProtector","dns"],aP=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];var aD=r(37491);let aB=["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"].map(e=>new aD.Netmask(e));function aN(e){return(0,iN.C)(e)?function(e){for(let t of aB)if(t.contains(e))return!0;return!1}(e):(0,iN.aY)(e)?/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^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(e)||/^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(e)||/^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(e)||/^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(e)||/^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(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e):void 0}function aL(e){try{let{address:t}=e.nodeAddress();return!!aN(t)}catch{return!0}}function ax(e,t){let r=function(e,t){let r=aL(e.multiaddr),n=aL(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;let n=function(e,t){let r=sr.exactMatch(e.multiaddr),n=sr.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);return 0!==n?n:e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}class aO extends Event{constructor(e,t){super(e),this.detail=t}}function aM(e){let t=[e2.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function aU(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map(e=>({name:e.name,type:e2[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:e2[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?(0,r5.B)(e.data):e.data}))}}function aF(e,t={}){let r=new oj({concurrency:t.queryConcurrency??4});return async(t,n={})=>{let i=new URLSearchParams;i.set("name",t),aM(n.types).forEach(e=>{i.append("type",e2[e])}),n.onProgress?.(new aO("dns:query",{detail:t}));let s=await r.add(async()=>{let t=await fetch(`${e}?${i}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);let r=aU(await t.json());return n.onProgress?.(new aO("dns:response",{detail:r})),r},{signal:n.signal});if(null==s)throw Error("No DNS response received");return s}}var aK=r(50762);class aV{lru;constructor(e){this.lru=aK(e)}get(e,t){let r=!0,n=[];for(let i of t){let t=this.getAnswers(e,i);if(0===t.length){r=!1;break}n.push(...t)}if(r)return aU({answers:n})}getAnswers(e,t){let r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){let e=n.filter(e=>e.expires>Date.now()).map(({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:e2[t.type]}));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){let r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+(t.TTL??60)*1e3,value:t}),this.lru.set(r,n)}remove(e,t){let r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class aH{resolvers;cache;constructor(e){this.resolvers={},this.cache=new aV(e.cacheSize??1e3),Object.entries(e.resolvers??{}).forEach(([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t}),null==this.resolvers["."]&&(this.resolvers["."]=[aF("https://cloudflare-dns.com/dns-query"),aF("https://dns.google/resolve")])}async query(e,t={}){let r=aM(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new aO("dns:cache",{detail:n})),n;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),o=[];for(let n of s){if(t.signal?.aborted===!0)break;try{let i=await n(e,{...t,types:r});for(let t of i.Answer)this.cache.add(e,t);return i}catch(e){o.push(e),t.onProgress?.(new aO("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(ey=e2||(e2={}))[ey.A=1]="A",ey[ey.CNAME=5]="CNAME",ey[ey.TXT=16]="TXT",ey[ey.AAAA=28]="AAAA";let{code:a$}=(0,r(27304).Ev)("dnsaddr"),aq=async function(e,t={}){let r=t.maxRecursiveDepth??32;if(0===r)throw new rX.sv("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,n]=e.stringTuples().find(([e])=>e===a$)??[],i=t?.dns??function(e={}){return new aH(e)}(),s=await i.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[e2.TXT]}),o=e.getPeerId(),a=[];for(let e of s.Answer){let n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n||null!=o&&!n.includes(o))continue;let i=(0,n0.HM)(n);if(n.startsWith("/dnsaddr")){let e=await i.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map(e=>e.toString()))}else a.push(i.toString())}return a};var az=r(18350);(eb=e3||(e3={})).NOT_STARTED_YET="The libp2p node is not started yet",eb.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",eb.NOT_FOUND="Not found",(ev=e4||(e4={})).ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",ev.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",ev.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",ev.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",ev.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",ev.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",ev.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",ev.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",ev.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",ev.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",ev.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",ev.ERR_DIALED_SELF="ERR_DIALED_SELF",ev.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",ev.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",ev.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",ev.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",ev.ERR_INVALID_KEY="ERR_INVALID_KEY",ev.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",ev.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",ev.ERR_INVALID_PEER="ERR_INVALID_PEER",ev.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",ev.ERR_NOT_FOUND="ERR_NOT_FOUND",ev.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",ev.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",ev.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",ev.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",ev.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",ev.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",ev.ERR_FIND_SELF="ERR_FIND_SELF",ev.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",ev.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",ev.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",ev.ERR_INVALID_CMS="ERR_INVALID_CMS",ev.ERR_MISSING_KEYS="ERR_MISSING_KEYS",ev.ERR_NO_KEY="ERR_NO_KEY",ev.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",ev.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",ev.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",ev.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",ev.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",ev.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",ev.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",ev.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",ev.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",ev.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",ev.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",ev.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",ev.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",ev.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",ev.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",ev.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",ev.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",ev.ERR_INVALID_RECORD="ERR_INVALID_RECORD",ev.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",ev.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",ev.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",ev.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",ev.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",ev.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED";let aj={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:aq},addressSorter:ax},transportManager:{faultTolerance:eO.FATAL_ALL}};async function aG(e){let t=az(aj,e);if(null===t.connectionProtector&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new rX.sv(e3.ERR_PROTECTOR_REQUIRED,e4.ERR_PROTECTOR_REQUIRED);if(!(await (0,nF.y5)(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new rX.sv("Private key doesn't match peer id",e4.ERR_INVALID_KEY);return t}function aW(e){let t;if((0,ar.I)(e))return{peerId:e,multiaddrs:[]};if(Array.isArray(e)||(e=[e]),e.length>0){let r=e[0].getPeerId();t=null==r?void 0:(0,nF.jE)(r),e.forEach(e=>{if(!(0,n0.h2)(e))throw new rX.sv("Invalid Multiaddr",e4.ERR_INVALID_MULTIADDR);let r=e.getPeerId();if(null==r){if(null!=t)throw new rX.sv("Multiaddrs must all have the same peer id or have no peer id",e4.ERR_INVALID_PARAMETERS)}else{let e=(0,nF.jE)(r);if(null==t||!t.equals(e))throw new rX.sv("Multiaddrs must all have the same peer id or have no peer id",e4.ERR_INVALID_PARAMETERS)}})}return{peerId:t,multiaddrs:e}}class aY 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 aQ(e,t,r,n){let i=new aY(n?.errorMessage,n?.errorCode);return r?.aborted===!0?Promise.reject(i):new Promise((s,o)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,l),n?.errorEvent!=null&&e.removeEventListener(n.errorEvent,c)}let l=e=>{try{if(n?.filter?.(e)===!1)return}catch(e){a(),o(e);return}a(),s(e)},c=e=>{a(),o(e.detail)},u=()=>{a(),o(i)};r?.addEventListener("abort",u),e.addEventListener(t,l),n?.errorEvent!=null&&e.addEventListener(n.errorEvent,c)})}class aJ{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=(0,t6.Z)(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new rX._L)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class aX{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,(0,iT.W)(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&t.signal?.aborted===!0,!0)&&(this.controller.abort(new rX._L),this.cleanup())}async join(e={}){let t=new aJ(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 t8(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)})}}class aZ extends tQ.L{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&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(0===this.size)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),0===this.running&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending{for(let t=0;t(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e)).catch(e=>{if("queued"===r.status){for(let e=0;e{e.abort(new rX._L)}),this.clear()}async onEmpty(e){0!==this.size&&await aQ(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.sizethis.size{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},i=e=>{r(e.detail)},s=()=>{r()},o=()=>{r(new rX.sv("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",o),r()}}}class a0 extends aZ{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}let a1="last-dial-failure",a2={minConnections:5,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:42e4,autoDialDiscoveredPeersDebounce:10};class a3{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){let r;this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??a2.minConnections,this.autoDialPriority=t.autoDialPriority??a2.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??a2.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??a2.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??a2.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??a2.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new a0({concurrency:t.autoDialConcurrency??a2.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",e=>{this.log.error("error during auto-dial",e.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(e=>{this.log.error(e)})}),e.events.addEventListener("peer:discovery",()=>{clearTimeout(r),r=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error(e)})},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 r=new oV(this.connectionManager.getDialQueue().map(e=>e.peerId).filter(Boolean)),n=await this.peerStore.all({filters:[t=>0===t.addresses.length?(this.log.trace("not autodialing %p because they have no addresses",t.id),!1):e.has(t.id)?(this.log.trace("not autodialing %p because they are already connected",t.id),!1):r.has(t.id)?(this.log.trace("not autodialing %p because they are already being dialed",t.id),!1):!this.queue.has(t.id)||(this.log.trace("not autodialing %p because they are already being autodialed",t.id),!1)]}),i=n.sort(()=>Math.random()>.5?1:-1),s=new o$;for(let e of i)s.has(e.id)||s.set(e.id,[...e.tags.values()].reduce((e,t)=>e+t.value,0));let o=i.sort((e,t)=>{let r=s.get(e.id)??0,n=s.get(t.id)??0;return r>n?-1:r{let t=e.metadata.get(a1);if(null==t)return!0;let r=parseInt((0,r5.B)(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs});for(let e of(this.log("selected %d/%d peers to dial",o.length,n.length),o))this.queue.add(async()=>{let t=this.connectionManager.getConnectionsMap().size;if(t>=this.minConnections){this.log("got enough connections now %d/%d",t,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",e.id),await this.connectionManager.openConnection(e.id,{priority:this.autoDialPriority})},{peerId:e.id}).catch(e=>{this.log.error("could not connect to peerStore stored peer",e)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}}let a4=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function a6(e,t){let r=e?.streams?.map(e=>e.protocol)??[],n=t?.closableProtocols??a4;if(!(r.filter(e=>null!=e&&!n.includes(e)).length>0))try{await e?.close(t)}catch(t){e?.abort(t)}}let a5={maxConnections:100,allow:[]};class a8{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??a5.maxConnections,this.allow=t.allow??a5.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(e=>{this.log.error(e)})})}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 r=new o$;for(let t of e){let e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{let t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce((e,t)=>e+t.value,0))}catch(e){"ERR_NOT_FOUND"!==e.code&&this.log.error("error loading peer tags",e)}}}let n=this.sortConnections(e,r),i=Math.max(t-this.maxConnections,0),s=[];for(let e of n)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some(t=>e.remoteAddr.toString().startsWith(t.toString()))||s.push(e),s.length===i)break;await Promise.all(s.map(async e=>{await a6(e,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort((e,t)=>{let r=e.timeline.open,n=t.timeline.open;return rn?-1:0}).sort((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0).sort((e,t)=>e.streams.length>t.streams.length?1:e.streams.length{let n=t.get(e.remotePeer)??0,i=t.get(r.remotePeer)??0;return n>i?1:ne.options.priority>t.options.priority?-1:e.options.prioritye.toString())),n}let lt={addressSorter:ax,maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3};class lr{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){for(let[r,n]of(this.addressSorter=t.addressSorter??lt.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??lt.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??lt.maxDialQueueLength,this.dialTimeout=t.dialTimeout??lt.dialTimeout,this.connections=t.connections??new o$,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,(0,iT.W)(1/0,this.shutDownController.signal),Object.entries(t.resolvers??{})))n0.s_.set(r,n);this.queue=new a9({concurrency:t.maxParallelDials??lt.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",e=>{this.log.error("error in dial queue",e.detail)})}start(){this.shutDownController=new AbortController,(0,iT.W)(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:r,multiaddrs:n}=aW(e),i=Array.from(this.connections.values()).flat().find(e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find(t=>t.equals(e.remoteAddr))));if(null!=i)return this.log("already connected to %a",i.remoteAddr),i;let s=this.queue.queue.find(e=>{if(r?.equals(e.options.peerId)===!0)return!0;let t=e.options.multiaddrs;if(null==t)return!1;for(let e of n)if(t.has(e.toString()))return!0;return!1});if(null!=s){for(let e of(this.log("joining existing dial target for %p",r),n))s.options.multiaddrs.add(e.toString());return s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new rX.sv("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",r,n.map(e=>e.toString())),this.queue.add(async e=>{let t;let n=this.createDialAbortController(e?.signal);try{(t=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:n})).map(({multiaddr:e})=>e.toString()).forEach(t=>{e?.multiaddrs.add(t)})}catch(e){throw n.clear(),e}try{let i=0,s=[];for(let o of t){if(i===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",i,r),new rX.sv("Peer had more than maxPeerAddrsToDial",e4.ERR_TOO_MANY_ADDRESSES);i++;try{let t=await this.components.transportManager.dial(o.multiaddr,{...e,signal:n});return this.log("dial to %a succeeded",o.multiaddr),t}catch(e){if(this.log.error("dial failed to %a",o.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[a1]:(0,r0.m)(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(n.aborted)throw new rX.sv(e.message,rX.l9);s.push(e)}}if(1===s.length)throw s[0];throw new rX.J5(s,"All multiaddr dials failed",e4.ERR_TRANSPORT_DIAL_FAILED)}finally{n.clear()}},{peerId:r,priority:t.priority??ln,multiaddrs:new Set(n.map(e=>e.toString())),signal:t.signal})}createDialAbortController(e){let t=a7([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return(0,iT.W)(1/0,t),t}async calculateMultiaddrs(e,t=new Set,r={}){let n=[...t].map(e=>({multiaddr:(0,n0.HM)(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new rX.sv("Tried to dial self",e4.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new rX.sv("The dial request is blocked by gater.allowDialPeer",e4.ERR_PEER_DIAL_INTERCEPTED);if(0===n.length){this.log("loading multiaddrs for %p",e);try{let t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map(({multiaddr:e})=>e.toString()))}catch(e){if(e.code!==e4.ERR_NOT_FOUND)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{let t=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,n.map(({multiaddr:e})=>e.toString())),n.push(...t.multiaddrs.map(e=>({multiaddr:e,isCertified:!1})))}catch(t){t.code!==e4.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let i=(await Promise.all(n.map(async e=>{let t=await le(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map(e=>({multiaddr:e,isCertified:!1}))}))).flat();if(null!=e){let t=`/p2p/${e.toString()}`;i=i.map(e=>{let r=e.multiaddr.protos().pop();return r?.path===!0?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e})}let s=i.filter(t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;let r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)}),o=new Map;for(let e of s){let t=e.multiaddr.toString(),r=o.get(t);if(null!=r){r.isCertified=r.isCertified||e.isCertified||!1;continue}o.set(t,e)}let a=[...o.values()];if(0===a.length)throw new rX.sv("The dial request has no valid addresses",e4.ERR_NO_VALID_ADDRESSES);let l=[];for(let e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||l.push(e);let c=l.sort(this.addressSorter);if(0===c.length)throw new rX.sv("The connection gater denied all addresses in the dial request",e4.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:e})=>e.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",c.map(({multiaddr:e})=>e.toString())),c}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let r=await this.calculateMultiaddrs(void 0,new Set(e.map(e=>e.toString())),t);if(!1===t.runOnTransientConnection)return null!=r.find(e=>!sr.matches(e.multiaddr));return!0}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}let ln=50,li={minConnections:5,maxConnections:100,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:42e4,autoDialDiscoveredPeersDebounce:10};class ls{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??li.maxConnections;let r=t.minConnections??li.minConnections;if(this.maxConnections(0,n0.HM)(e)),this.deny=(t.deny??[]).map(e=>(0,n0.HM)(e)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??li.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new sv({points:t.inboundConnectionThreshold??li.inboundConnectionThreshold,duration:1}),this.autoDial=new a3({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??li.autoDialConcurrency,autoDialPriority:t.autoDialPriority??li.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??li.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??li.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??li.autoDialMaxQueueLength}),this.connectionPruner=new a8({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new lr(e,{addressSorter:t.addressSorter??ax,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:aq},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 r of t)"inbound"===r.direction?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 r of t)for(let t of r.streams){let r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let r of t){let t={};for(let e of r.streams){let r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(let[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}let t={};for(let[r,n]of Object.entries(e)){let e=Math.floor(.9*(n=n.sort((e,t)=>e-t)).length);t[r]=n[e]}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:[e=>e.tags.has("keep-alive")]});await Promise.all(e.map(async e=>{await this.openConnection(e.id).catch(e=>{this.log.error(e)})}))}).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 r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(e=>{this.log.error(e)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let r=t.remotePeer,n=this.connections.get(r),i=!1;null!=n?n.push(t):(i=!0,this.connections.set(r,[t])),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),i&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let r=t.remotePeer,n=this.connections.get(r);null!=n&&n.length>1?(n=n.filter(e=>e.id!==t.id),this.connections.set(r,n)):null!=n&&(this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(let e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new rX.sv("Not started",e4.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:r}=aW(e);if(null!=r&&!0!==t.force){this.log("dial %p",r);let e=this.getConnections(r).find(e=>!e.transient);if(null!=e)return this.log("had an existing non-transient connection to %p",r),e}let n=await this.dialQueue.dial(e,{...t,priority:t.priority??ln}),i=this.connections.get(n.remotePeer);null==i&&(i=[],this.connections.set(n.remotePeer,i));let s=!1;for(let e of i)e.id===n.id&&(s=!0);return s||i.push(n),n}async closeConnections(e,t={}){let r=this.connections.get(e)??[];await Promise.all(r.map(async e=>{try{await e.close(t)}catch(t){e.abort(t)}}))}async acceptIncomingConnection(e){if(this.deny.some(t=>e.remoteAddr.toString().startsWith(t.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(t=>e.remoteAddr.toString().startsWith(t.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 t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(e=>(0,n0.HM)(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}var lo=r(10637);class la{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(0===this.routers.length)throw new rX.sv("No content routers available",e4.ERR_NO_ROUTERS_AVAILABLE);let r=new oV;for await(let n of(0,lo.Z)(...this.routers.map(r=>r.findProviders(e,t))))null!=n&&(n.multiaddrs.length>0&&await this.components.peerStore.merge(n.id,{multiaddrs:n.multiaddrs}),r.has(n.id)||(r.add(n.id),yield n))}async provide(e,t={}){if(0===this.routers.length)throw new rX.sv("No content routers available",e4.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async r=>{await r.provide(e,t)}))}async put(e,t,r){if(!this.isStarted())throw new rX.sv(e3.NOT_STARTED_YET,e4.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async n=>{await n.put(e,t,r)}))}async get(e,t){if(!this.isStarted())throw new rX.sv(e3.NOT_STARTED_YET,e4.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async r=>r.get(e,t)))}}let ll=globalThis.CustomEvent??Event;async function*lc(e,t={}){let r,n=t.concurrency??1/0;n<1&&(n=1/0);let i=null!=t.ordered&&t.ordered,s=new EventTarget,o=[],a=(0,t6.Z)(),l=(0,t6.Z)(),c=!1,u=!1;function h(){return i?o[0]?.done:!!o.find(e=>e.done)}for(s.addEventListener("task-complete",()=>{l.resolve()}),Promise.resolve().then(async()=>{try{for await(let t of e){if(o.length===n&&(a=(0,t6.Z)(),await a.promise),u)break;let e={done:!1};o.push(e),t().then(t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new ll("task-complete"))},t=>{e.done=!0,e.err=t,s.dispatchEvent(new ll("task-complete"))})}c=!0,s.dispatchEvent(new ll("task-complete"))}catch(e){r=e,s.dispatchEvent(new ll("task-complete"))}});;){if(h()||(l=(0,t6.Z)(),await l.promise),null!=r)throw r;if(i?yield*function*(){for(;o.length>0&&o[0].done;){let e=o[0];if(o.shift(),e.ok)yield e.value;else throw u=!0,a.resolve(),e.err;a.resolve()}}():yield*function*(){for(;h();)for(let e=0;e(async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}})())))if(null!=n)return n.multiaddrs.length>0&&await this.peerStore.merge(n.id,{multiaddrs:n.multiaddrs}),n;throw new rX.sv(e3.NOT_FOUND,e4.ERR_NOT_FOUND)}async *getClosestPeers(e,t={}){if(0===this.routers.length)throw new rX.sv("No peer routers available",e4.ERR_NO_ROUTERS_AVAILABLE);let r=this,n=new oV;for await(let i of lc(async function*(){for await(let n of(0,lo.Z)(...r.routers.map(r=>r.getClosestPeers(e,t))))yield async()=>{if(0===n.multiaddrs.length)try{n=await r.findPeer(n.id,{...t,useCache:!1})}catch(e){r.log.error("could not find peer multiaddrs",e);return}return n}}()))null!=i&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),n.has(i.id)||(n.add(i.id),yield i))}}class lh extends tQ.L{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,(0,iT.W)(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,(0,iT.W)(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async *walk(e){this.walking||this.startWalk(),this.walkers++;let t=a7([this.shutdownController.signal,e?.signal]);(0,iT.W)(1/0,t);try{for(;;){this.needNext?.resolve(),this.needNext=(0,t6.Z)();let e=await aQ(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,(0,iT.W)(1/0,this.walkController.signal);let e=a7([this.walkController.signal,this.shutdownController.signal]);(0,iT.W)(1/0,e);let t=Date.now(),r=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let t of this.peerRouting.getClosestPeers((0,sO.Z)(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",t.id),r++,this.safeDispatchEvent("walk:peer",{detail:t}),1===this.walkers&&null!=this.needNext&&await t8(this.needNext.promise,e)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}}).catch(e=>{this.log.error("randomwalk errored",e)}).finally(()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1})}}class ld{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(null==t)throw new rX.sv(`No handler registered for protocol ${e}`,e4.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new rX.sv(`Handler already registered for protocol ${e}`,e4.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let n=az.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(e=>{this.handlers.delete(e)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(null==t)throw new rX.sv("invalid topology",e4.ERR_INVALID_PARAMETERS);let r=`${(1e9*Math.random()).toString(36)}${Date.now()}`,n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(let[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(e=>{for(let r of e.protocols){let e=this.topologies.get(r);if(null!=e)for(let r of e.values())r.filter?.has(t)!==!1&&(r.filter?.remove(t),r.onDisconnect?.(t))}}).catch(e=>{e.code!==e4.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)})}_onPeerUpdate(e){let{peer:t,previous:r}=e.detail;for(let e of(r?.protocols??[]).filter(e=>!t.protocols.includes(e))){let r=this.topologies.get(e);if(null!=r)for(let e of r.values())e.filter?.has(t.id)!==!1&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(let e of t){let t=this.topologies.get(e);if(null!=t)for(let e of t.values())r.transient&&!0!==e.notifyOnTransient||e.filter?.has(n)===!0||(e.filter?.add(n),e.onConnect?.(n,r))}}}class lp extends Map{metric;constructor(e){super();let{name:t,metrics:r}=e;this.metric=r.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)}}class lf{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=function(e){let{name:t,metrics:r}=e;return null!=r?new lp({name:t,metrics:r}):new Map}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??eO.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(null==t)throw new rX.sv("Transport must have a valid tag",e4.ERR_INVALID_KEY);if(this.transports.has(t))throw new rX.sv(`There is already a transport with the tag ${t}`,e4.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,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){let t=r.pop();null!=t&&e.push(t.close())}for(let t of(await Promise.all(e),this.log("all listeners closed"),this.listeners.keys()))this.listeners.set(t,[]);this.started=!1}async dial(e,t){let r=this.dialTransportForMultiaddr(e);if(null==r)throw new rX.sv(`No transport available for address ${String(e)}`,e4.ERR_TRANSPORT_UNAVAILABLE);try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=e4.ERR_TRANSPORT_DIAL_FAILED),e}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let r of t)e=[...e,...r.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 rX.sv("Not started",e4.ERR_NODE_NOT_STARTED);if(null==e||0===e.length){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[r,n]of this.transports.entries()){let i=n.listenFilter(e),s=[];for(let e of i){this.log("creating listener for %s on %a",r,e);let t=n.createListener({upgrader:this.components.upgrader}),i=this.listeners.get(r)??[];null==i&&(i=[],this.listeners.set(r,i)),i.push(t),t.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})}),t.addEventListener("close",()=>{let e=i.findIndex(e=>e===t);i.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})}),s.push(t.listen(e))}if(0===s.length){t.push(r);continue}if(null==(await Promise.allSettled(s)).find(e=>"fulfilled"===e.status)&&this.faultTolerance!==eO.NO_FATAL)throw new rX.sv(`Transport (${r}) could not listen on any available address`,e4.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===eO.FATAL_ALL)throw new rX.sv(e,e4.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),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)}}let lg="/multistream/1.0.0",lm=(0,r0.m)("\n");async function ly(e,t,r){await e.write(t,r)}async function lb(e,t,r){await e.writeV(t,r)}async function lv(e,t){let r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==lm[0])throw t.log.error("Invalid mss message - missing newline",r),new rX.sv("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function lw(e,t){let r=await lv(e,t);return(0,r5.B)(r.subarray())}async function lE(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);let n=rn(e,{...r,maxDataLength:1024,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");let e=await lw(n,r);if(r.log.trace('handle: read "%s"',e),e===lg){r.log.trace('handle: respond with "%s" for "%s"',lg,e),await ly(n,(0,r0.m)(`${lg} +`),r),r.log.trace('handle: responded with "%s" for "%s"',lg,e);continue}if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await ly(n,(0,r0.m)(`${e} +`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"===e){let i=new tR.H(...t.map(e=>tf.c.single((0,r0.m)(`${e} +`))),(0,r0.m)("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await ly(n,i,r),r.log.trace('handle: responded with "%s" for %s',t,e);continue}r.log('handle: respond with "na" for "%s"',e),await ly(n,(0,r0.m)("na\n"),r),r.log('handle: responded with "na" for "%s"',e)}}async function lS(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){let n=e.sink.bind(e),i=e.source,s=!1,o=!1,a=(0,t6.Z)(),l=!1,c=!1,u=(0,t6.Z)(),h=!1,d=!1,p=(0,t6.Z)(),f=rn({sink:n,source:i},{...r,maxDataLength:1024});async function g(){if(o){r.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}o=!0;try{l||(r.log.trace("optimistic: doing send protocol for %s stream",t),await m()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await y())}finally{o=!1,s=!0,a.resolve()}}async function m(){if(c){await u.promise;return}c=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',lg,t),await f.writeV([(0,r0.m)(`${lg} +`),(0,r0.m)(`${t} +`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',lg,t)}finally{l=!0,c=!1,u.resolve()}}async function y(){if(d){await p.promise;return}d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await lw(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===lg&&(e=await lw(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new rX.sv("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}if(e.sink=async e=>{let{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(let i of e){if(c&&await u.promise,l)yield i;else{c=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',lg,t,i.byteLength);let e=`${t} +`;yield new tR.H(Uint8Array.from([19]),(0,r0.m)(`${lg} +`),rt.cv(e.length),(0,r0.m)(e),i).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',lg,t,i.byteLength),l=!0,c=!1,u.resolve(),g().catch(e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)})}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){let t=e.closeRead.bind(e);e.closeRead=async e=>{s||await g().catch(e=>{r.log.error("could not negotiate protocol before close read",e)}),await t(e)}}if(null!=e.closeWrite){let t=e.closeWrite.bind(e);e.closeWrite=async e=>{s||await g().catch(e=>{r.log.error("could not negotiate protocol before close write",e)}),await t(e)}}if(null!=e.close){let t=e.close.bind(e);e.close=async e=>{let r=[];c&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await t8(Promise.all(r),e?.signal):(s=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);let n=rn(e,{...r,maxDataLength:1024}),i=t.shift();if(null==i)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',lg,i);let s=(0,r0.m)(`${lg} +`),o=(0,r0.m)(`${i} +`);await lb(n,[s,o],r),r.log.trace("select: reading multistream-select header");let a=await lw(n,r);if(r.log.trace('select: read "%s"',a),a===lg&&(r.log.trace("select: reading protocol response"),a=await lw(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(let e of t){r.log.trace('select: write "%s"',e),await ly(n,(0,r0.m)(`${e} +`),r),r.log.trace("select: reading protocol response");let t=await lw(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new rX.sv("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}let lA=Symbol.for("@libp2p/connection");class lI{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:r,newStream:n,close:i,abort:s,getStreams:o}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,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}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=i,this._abort=s,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[lA]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new rX.sv("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new rX.sv("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new rX.sv("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){let t=AbortSignal.timeout(500);(0,iT.W)(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(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}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 l_(e,t,r){let n=0;return r.streams.forEach(r=>{r.direction===t&&r.protocol===e&&n++}),n}class lT{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(e=>{this.connectionEncryption.set(e.protocol,e)}),this.muxers=new Map,t.muxers.forEach(e=>{this.muxers.set(e.protocol,e)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,r){let n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new rX.sv(`The multiaddr connection is blocked by gater.${r}`,e4.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){let r,n,i,s,o;if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new rX.sv("connection denied",e4.ERR_CONNECTION_DENIED);let a=AbortSignal.timeout(this.inboundUpgradeTimeout),l=()=>{e.abort(new rX.sv("inbound upgrade timeout",rX.l9))};a.addEventListener("abort",l,{once:!0}),(0,iT.W)(1/0,a);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new rX.sv("The multiaddr connection is blocked by gater.acceptConnection",e4.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(t?.skipProtection!==!0){let t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,t?.skipEncryption!==!0){({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(a));let e={...a,...r};await this.shouldBlockConnection(n,e,"denyInboundEncryptedConnection")}else{let t=e.remoteAddr.getPeerId();if(null==t)throw new rX.sv("inbound connection that skipped encryption must have a peer id",e4.ERR_INVALID_MULTIADDR);let r=(0,nF.jE)(t);o="native",n=r}if(i=r,t?.muxerFactory!=null)s=t.muxerFactory;else if(this.muxers.size>0){let e=await this._multiplexInbound({...a,...r},this.muxers);s=e.muxerFactory,i=e.stream}}catch(t){throw e.log.error("failed to upgrade inbound connection",t),t}return await this.shouldBlockConnection(n,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:o,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:s,remotePeer:n,transient:t?.transient})}finally{a.removeEventListener("abort",l),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let r,n,i,s,o,a;let l=e.remoteAddr.getPeerId();null!=l&&(r=(0,nF.jE)(l),await this.shouldBlockConnection(r,e,"denyOutboundConnection")),this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let c=e;if(t?.skipProtection!==!0){let t=this.components.connectionProtector;null!=t&&(c=await t.protect(e))}try{if(n=c,t?.skipEncryption!==!0){({conn:n,remotePeer:i,protocol:o}=await this._encryptOutbound(c,r));let e={...c,...n};await this.shouldBlockConnection(i,e,"denyOutboundEncryptedConnection")}else{if(null==r)throw new rX.sv("Encryption was skipped but no peer id was passed",e4.ERR_INVALID_PEER);o="native",i=r}if(s=n,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let e=await this._multiplexOutbound({...c,...n},this.muxers);a=e.muxerFactory,s=e.stream}}catch(t){throw e.log.error("failed to upgrade outbound connection",t),await e.close(t),t}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:o,direction:"outbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:i,transient:t?.transient})}_createConnection(e){let t,r,n;let{cryptoProtocol:i,direction:s,maConn:o,upgradedConn:a,remotePeer:l,muxerFactory:c,transient:u}=e;null!=c&&(t=c.createStreamMuxer({direction:s,onIncomingStream:e=>{null!=n&&Promise.resolve().then(async()=>{let t=this.components.registrar.getProtocols(),{stream:r,protocol:i}=await lE(e,t,{log:e.log,yieldBytes:!1});if(null==n)return;n.log("incoming stream opened on %s",i);let s=function(e,t){try{let{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if(e.code!==e4.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(i,this.components.registrar);if(l_(i,"inbound",n)===s){let t=new rX.sv(`Too many inbound protocol streams for protocol "${i}" - limit ${s}`,e4.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw e.abort(t),t}e.source=r.source,e.sink=r.sink,e.protocol=i,null!=r.closeWrite&&(e.closeWrite=r.closeWrite),null!=r.closeRead&&(e.closeRead=r.closeRead),null!=r.close&&(e.close=r.close),await this.components.peerStore.merge(l,{protocols:[i]}),this.components.metrics?.trackProtocolStream(e,n),this._onStream({connection:n,stream:e,protocol:i})}).catch(async t=>{n.log.error("error handling incoming stream id %s",e.id,t.message,t.code,t.stack),null==e.timeline.close&&await e.close()})}}),r=async(e,r={})=>{if(null==t)throw new rX.sv("Stream is not multiplexed",e4.ERR_MUXER_UNAVAILABLE);n.log("starting new stream for protocols %s",e);let i=await t.newStream();n.log.trace("started new stream %s for protocols %s",i.id,e);try{if(null==r.signal){i.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let t=AbortSignal.timeout(3e4);(0,iT.W)(1/0,t),r={...r,signal:t}}i.log.trace("selecting protocol from protocols %s",e);let{stream:t,protocol:s}=await lS(i,e,{...r,log:i.log,yieldBytes:!0});i.log("selected protocol %s",s);let o=function(e,t,r={}){try{let{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==e4.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,r),a=l_(s,"outbound",n);if(a>=o){let e=new rX.sv(`Too many outbound protocol streams for protocol "${s}" - ${a}/${o}`,e4.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw i.abort(e),e}return await this.components.peerStore.merge(l,{protocols:[s]}),i.source=t.source,i.sink=t.sink,i.protocol=s,null!=t.closeWrite&&(i.closeWrite=t.closeWrite),null!=t.closeRead&&(i.closeRead=t.closeRead),null!=t.close&&(i.close=t.close),this.components.metrics?.trackProtocolStream(i,n),i}catch(t){if(n.log.error("could not create new stream for protocols %s",e,t),null==i.timeline.close&&i.abort(t),null!=t.code)throw t;throw new rX.sv(String(t),e4.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([t.sink(a.source),a.sink(t.source)]).catch(e=>{n.log.error("error piping data through muxer",e)}));let h=o.timeline;return o.timeline=new Proxy(h,{set:(...e)=>(null!=n&&"close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===n.status&&await n.close()}catch(e){n.log.error("error closing connection after timeline close",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:n})}})().catch(e=>{n.log.error("error thrown while dispatching connection:close event",e)}),Reflect.set(...e))}),o.timeline.upgraded=Date.now(),n=new lI({remoteAddr:o.remoteAddr,remotePeer:l,status:"open",direction:s,timeline:o.timeline,multiplexer:t?.protocol,encryption:i,transient:u,logger:this.components.logger,newStream:r??(()=>{throw new rX.sv("connection is not multiplexed",e4.ERR_CONNECTION_NOT_MULTIPLEXED)}),getStreams:()=>null!=t?t.streams:[],close:async e=>{null!=t&&(n.log.trace("close muxer"),await t.close(e)),n.log.trace("close maconn"),await o.close(e),n.log.trace("closed maconn")},abort:e=>{o.abort(e),null!=t&&t.abort(e)}}),this.events.safeDispatchEvent("connection:open",{detail:n}),n}_onStream(e){let{connection:t,stream:r,protocol:n}=e,{handler:i,options:s}=this.components.registrar.getHandler(n);if(t.transient&&!0!==s.runOnTransientConnection)throw new rX.sv("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");i({connection:t,stream:r})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:r,protocol:n}=await lE(e,t,{log:e.log}),i=this.connectionEncryption.get(n);if(null==i)throw Error(`no crypto module found for ${n}`);return e.log("encrypting inbound connection using",n),{...await i.secureInbound(this.components.peerId,r),protocol:n}}catch(t){throw e.log.error("encrypting inbound connection failed",t),new rX.sv(t.message,e4.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let r=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",r);try{e.log.trace("selecting encrypter from %s",r);let{stream:n,protocol:i}=await lS(e,r,{log:e.log,yieldBytes:!0}),s=this.connectionEncryption.get(i);if(null==s)throw Error(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %p using %s",t,s),{...await s.secureOutbound(this.components.peerId,n,t),protocol:i}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new rX.sv(r.message,e4.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);let{stream:n,protocol:i}=await lS(e,r,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let s=t.get(i);return{stream:n,muxerFactory:s}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new rX.sv(String(t),e4.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{let{stream:n,protocol:i}=await lE(e,r,{log:e.log}),s=t.get(i);return{stream:n,muxerFactory:s}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new rX.sv(String(t),e4.ERR_MUXER_UNAVAILABLE)}}}class lC extends tQ.L{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new tQ.L,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{let t=r(e),n=this.dispatchEvent(new tQ.A(e.type,{detail:e.detail}));return t||n},(0,iT.W)(1/0,t),this.peerId=e.peerId,this.logger=e.logger??oF(),this.log=this.logger.forComponent("libp2p"),this.services={};let n=this.components=function(e={}){let t=new aR(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!aP.includes(r)){let e=t.components[r];if(null==e&&!ak.includes(r))throw new rX.sv(`${r} not set`,"ERR_SERVICE_MISSING");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"1.6.0"},logger:this.logger,events:t,datastore:e.datastore??new aI,connectionGater:function(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!aN(`${t[0][1]}`)},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new am(n,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),n.events.addEventListener("peer:update",e=>{if(null==e.detail.previous){let t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map(e=>e.multiaddr)};n.events.safeDispatchEvent("peer:discovery",{detail:t})}}),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(n)),this.components.upgrader=new lT(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components))),muxers:(e.streamMuxers??[]).map((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new lf(this.components,e.transportManager)),this.configureComponent("connectionManager",new ls(this.components,e.connectionManager)),this.configureComponent("registrar",new ld(this.components)),this.configureComponent("addressManager",new aC(this.components,e.addresses));let i=(e.peerRouters??[]).map((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new lu(this.components,{routers:i}));let s=(e.contentRouters??[]).map((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new la(this.components,{routers:s})),this.configureComponent("randomWalk",new lh(this.components)),(e.peerDiscovery??[]).forEach((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",e=>{this.#L(e)})}),e.transports?.forEach((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))}),null!=e.services)for(let t of Object.keys(e.services)){let r=(0,e.services[t])(this.components);if(null==r){this.log.error("service factory %s returned null or undefined instance",t);continue}this.services[t]=r,this.configureComponent(t,r),null!=r[ox]&&(this.log("registering service %s for content routing",t),s.push(r[ox])),null!=r[oO]&&(this.log("registering service %s for peer routing",t),i.push(r[oO])),null!=r[nZ.J]&&(this.log("registering service %s for peer discovery",t),r[nZ.J].addEventListener?.("peer",e=>{this.#L(e)}))}}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){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(){"started"===this.status&&(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 oV;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,r={}){if(null==t||0===(t=Array.isArray(t)?t:[t]).length)throw new rX.sv("no protocols were provided to open a stream",e4.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){(0,n0.h2)(e)&&(e=(0,nF.jE)(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{let t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if(e.code!==e4.ERR_NOT_FOUND)throw e}let r=(0,r6.z)([(0,r0.m)("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return(0,ik.lR)(n),await this.peerStore.patch(e,{publicKey:n}),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.handle(e,t,r)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.unhandle(e)}))}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)}#L(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(Error(e4.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(e=>{this.log.error(e)})}}async function lR(e={}){let t=e.peerId??=await (0,oH.n9)();if(null==t.privateKey)throw new rX.sv("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await (0,ik.r3)(t.privateKey),new lC(await aG(e))}async function lk(e={}){let t=await lR(e);return!1!==e.start&&await t.start(),t}function lP(e){return!!e}(ew=e6||(e6={})).Relay="relay",ew.Store="store",ew.LightPush="lightpush",ew.Filter="filter",(eE=e5||(e5={})).GENERIC_FAIL="Generic error",eE.ENCODE_FAILED="Failed to encode",eE.DECODE_FAILED="Failed to decode",eE.EMPTY_PAYLOAD="Payload is empty",eE.SIZE_TOO_BIG="Size is too big",eE.TOPIC_NOT_CONFIGURED="Topic not configured",eE.NO_PEER_AVAILABLE="No peer available",eE.REMOTE_PEER_FAULT="Remote peer fault",eE.REMOTE_PEER_REJECTED="Remote peer rejected",eE.REQUEST_TIMEOUT="Request timeout",(eS=e8||(e8={})).BACKWARD="backward",eS.FORWARD="forward",(eA=e9||(e9={})).BOOTSTRAP="bootstrap",eA.PEER_EXCHANGE="peer-exchange",eA.LOCAL="local-peer-cache",(eI=e7||(e7={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",eI.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",eI.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",eI.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(te||(te={})).CONNECTION_STATUS="waku:connection";let lD=e=>(0,r5.B)(e,"utf8"),lB=e=>(0,r0.m)(e,"utf8");class lN{numPeers;constructor(e){this.numPeers=e?.numPeersToUse??3}}let lL=new ts.Yd("sdk:filter");class lx{protocol;pubsubTopic;peers;receivedMessagesHashStr=[];subscriptionCallbacks;constructor(e,t,r){this.protocol=r,this.peers=t,this.pubsubTopic=e,this.subscriptionCallbacks=new Map}async subscribe(e,t){let r=Array.isArray(e)?e:[e];r.forEach(e=>{if(e.pubsubTopic!==this.pubsubTopic)throw Error(`Pubsub topic not configured: decoder is configured for pubsub topic ${e.pubsubTopic} but this subscription is for pubsub topic ${this.pubsubTopic}. Please create a new Subscription for the different pubsub topic.`)});let n=(0,ts.p3)(r),i=Array.from(n.keys()),s=this.peers.map(async e=>{await this.protocol.subscribe(this.pubsubTopic,e,i)}),o=await Promise.allSettled(s);this.handleErrors(o,"subscribe"),n.forEach((e,r)=>{this.subscriptionCallbacks.set(r,{decoders:e,callback:t})})}async unsubscribe(e){let t=this.peers.map(async t=>{await this.protocol.unsubscribe(this.pubsubTopic,t,e),e.forEach(e=>{this.subscriptionCallbacks.delete(e)})}),r=await Promise.allSettled(t);this.handleErrors(r,"unsubscribe")}async ping(){let e=this.peers.map(async e=>{await this.protocol.ping(e)}),t=await Promise.allSettled(e);this.handleErrors(t,"ping")}async unsubscribeAll(){let e=this.peers.map(async e=>{await this.protocol.unsubscribeAll(this.pubsubTopic,e)}),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear(),this.handleErrors(t,"unsubscribeAll")}async processIncomingMessage(e){let t=lD(function(e,t){let r=lB(e),n=lB(t.contentTopic),i=function(e){if(e)return function(e){let t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(e.valueOf())}(t.timestamp),s=function(e,t){let r=new Uint8Array((void 0)??e.reduce((e,t)=>e+t.length,0)),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([r,t.payload,n,t.meta,i].filter(lP));return(0,rj.J)(s)}(this.pubsubTopic,e));if(this.receivedMessagesHashStr.includes(t)){lL.info("Message already received, skipping");return}this.receivedMessagesHashStr.push(t);let{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);if(!n){lL.error("No subscription callback available for ",r);return}lL.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await lM(n,this.pubsubTopic,e)}handleErrors(e,t){let r=e.filter(e=>"rejected"===e.status).map(e=>e.reason);if(r.length===this.peers.length){let e=new Map;r.forEach(t=>{let r=t instanceof Error?t.message:String(t);e.set(r,(e.get(r)||0)+1)});let n=Array.from(e,([e,t])=>`${e} (occurred ${t} times)`).join(", ");throw Error(`Error ${t} all peers: ${n}`)}r.length>0?lL.warn(`Some ${t} failed. These will be refreshed with new peers`,r):lL.info(`${t} successful for all peers`)}}class lO extends lN{protocol;activeSubscriptions=new Map;async handleIncomingMessage(e,t){let r=this.getActiveSubscription(e);if(!r){lL.error(`No subscription locally registered for topic ${e}`);return}await r.processIncomingMessage(t)}constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new tT(this.handleIncomingMessage.bind(this),e,t),this.activeSubscriptions=new Map}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}async createSubscription(e){let t="string"==typeof e?e:ts.yf(e)?.[0];(0,ts.Qu)(t,this.protocol.pubsubTopics);let r=await this.protocol.getPeers();if(0===r.length)throw Error("No peer found to initiate subscription.");return lL.info(`Creating filter subscription with ${r.length} peers: `,r.map(e=>e.id.toString())),this.getActiveSubscription(t)??this.setActiveSubscription(t,new lx(t,r,this.protocol))}async subscribe(e,t){let r=this.getPubsubTopics(e);if(0===r.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(r.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");let n=await this.createSubscription(r[0]);await n.subscribe(e,t);let i=Array.from((0,ts.p3)(Array.isArray(e)?e:[e]).keys());return async()=>{await n.unsubscribe(i)}}toSubscriptionIterator(e){return(0,ts.B2)(this,e)}getPubsubTopics(e){return Array.isArray(e)?0===e.length?[]:[...new Set(e.map(e=>e.pubsubTopic))]:[e.pubsubTopic]}}async function lM(e,t,r){let{decoders:n,callback:i}=e,{contentTopic:s}=r;if(!s){lL.warn("Message has no content topic, skipping");return}try{let e=n.map(e=>e.fromProtoObj(t,r).then(e=>e||Promise.reject("Decoding failed"))),s=await Promise.any(e);await i(s)}catch(e){lL.error("Error decoding message",e)}}let lU=new ts.Yd("sdk:light-push");class lF extends lN{protocol;constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new tD(e,t)}async send(e,t){let r=[],n=[],{pubsubTopic:i}=e;try{(0,ts.Qu)(i,this.protocol.pubsubTopics)}catch(e){return lU.error("Failed to send waku light push: pubsub topic not configured"),{failures:[{error:tC.K1.TOPIC_NOT_CONFIGURED}],successes:[]}}let s=await this.protocol.getPeers();if(!s.length)return{successes:r,failures:[{error:tC.K1.NO_PEER_AVAILABLE}]};let o=s.map(r=>this.protocol.send(e,t,r));for(let e of(await Promise.allSettled(o)))if("fulfilled"===e.status){let{failure:t,success:i}=e.value;i&&r.push(i),t&&n.push(t)}else lU.error("Failed to send message to peer",e.reason),n.push({error:tC.K1.GENERIC_FAIL});return{successes:r,failures:n}}}let lK=new ts.Yd("waku:store:protocol");class lV extends lN{protocol;constructor(e,t){super({numPeersToUse:1}),this.protocol=new tM(e,t)}async *queryGenerator(e,t){let{pubsubTopic:r,contentTopics:n,decodersAsMap:i}=this.validateDecodersAndPubsubTopic(e,t),s=this.constructOptions(r,n,t),o=(await this.protocol.getPeers({numPeers:this.numPeers,maxBootstrapPeers:1}))[0];if(!o)throw Error("No peers available to query");for await(let e of this.protocol.queryPerPage(s,i,o))yield e}async queryWithOrderedCallback(e,t,r){for await(let n of this.queryGenerator(e,r))if(await this.processMessages(n,t,r))break}async queryWithPromiseCallback(e,t,r){let n=!1;for await(let i of this.queryGenerator(e,r)){let e=i.map(async e=>{n||(n=!!await t(e))});if(await Promise.all(e),n)break}}createCursor(e){if(!e||!e.timestamp||!e.payload||!e.contentTopic)throw Error("Message is missing required fields");let t=(0,tJ.iY)(e.contentTopic),r=(0,rj.J)((0,tJ.zo)([t,e.payload])),n=BigInt(e.timestamp.getTime())*BigInt(1e6);return{digest:r,pubsubTopic:e.pubsubTopic,senderTime:n,receiverTime:n}}validateDecodersAndPubsubTopic(e,t){if(0===e.length)throw Error("No decoders provided");let r=Array.from(new Set(e.map(e=>e.pubsubTopic)));if(r.length>1)throw Error("API does not support querying multiple pubsub topics at once");let n=r[0];if((0,ts.Qu)(n,this.protocol.pubsubTopics),t?.cursor?.pubsubTopic&&t.cursor.pubsubTopic!==n)throw Error(`Cursor pubsub topic (${t?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${n})`);let i=new Map;e.forEach(e=>{if(i.has(e.contentTopic))throw Error("API does not support different decoder per content topic");i.set(e.contentTopic,e)});let s=e.filter(e=>e.pubsubTopic===n).map(e=>e.contentTopic);if(0===s.length)throw Error("No decoders found for topic "+n);return{pubsubTopic:n,contentTopics:s,decodersAsMap:i}}constructOptions(e,t,r={}){let n,i;return r?.timeFilter&&(n=r.timeFilter.startTime,i=r.timeFilter.endTime),n||lK.warn("No start time provided"),i||lK.warn("No end time provided"),Object.assign({pubsubTopic:e,pageDirection:tC.$Q.BACKWARD,pageSize:10},r,{contentTopics:t,startTime:n,endTime:i})}async processMessages(e,t,r){let n=!1,i=(await Promise.all(e)).filter(ts.$K);return this.shouldReverseOrder(r)&&(i=i.reverse()),await Promise.all(i.map(async e=>{e&&!n&&(n=!!await t(e))})),n}shouldReverseOrder(e){return void 0===e?.pageDirection||e?.pageDirection===tC.$Q.BACKWARD}}async function lH(e={}){let t=await lQ(e),r=function(e={}){return t=>new lV(t,e)}(e),n=function(e={}){return t=>new lF(t,e)}(e);return new lj(e,t,r,n,t=>new lO(t,e))}async function l$(e,t,r){if(!e.filter)throw Error("Filter protocol missing from Waku node");let{shardInfo:n}=e.libp2p.components.metadata;if(!n)throw Error("Shard info missing from Waku node.");let i=(0,ts.yf)(n),s=(0,ts.L3)(t);if(!i.includes(s))throw Error("Content topic does not match any pubsub topic in shard info.");await e.dial(r),await tz(e,[tC.Uw.Filter]);let o=td(t,s);return o&&(o=o??o),{decoder:o,subscription:await e.filter.createSubscription(s)}}async function lq(e,t,r){r.waku=r.waku??await lH({shardInfo:{contentTopics:[e]}});let{decoder:n,subscription:i}=await l$(r.waku,e,r.peer);return await i.subscribe(n,t),{subscription:i,waku:r.waku}}let lz=new ts.Yd("waku");class lj{libp2p;relay;store;filter;lightPush;connectionManager;pubsubTopics;constructor(e,t,r,n,i,s){if(0==e.pubsubTopics.length)throw Error("At least one pubsub topic must be provided");this.pubsubTopics=e.pubsubTopics,this.libp2p=t,r&&(this.store=r(t)),i&&(this.filter=i(t)),n&&(this.lightPush=n(t)),s&&(this.relay=s(t));let o=e.pingKeepAlive||300,a=this.relay?e.relayKeepAlive||300:0,l=this.libp2p.peerId.toString();this.connectionManager=t1.create(l,t,{pingKeepAlive:o,relayKeepAlive:a},this.pubsubTopics,this.relay),lz.info("Waku node created",l,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}async dial(e,t){let r=t??[],n=(0,ar.I)(e)?e:(0,n0.HM)(e);void 0===t&&(this.relay&&r.push(tC.Uw.Relay),this.store&&r.push(tC.Uw.Store),this.filter&&r.push(tC.Uw.Filter),this.lightPush&&r.push(tC.Uw.LightPush));let i=[];return r.includes(tC.Uw.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(e=>i.push(e)):lz.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(tC.Uw.Store)&&(this.store?i.push(this.store.protocol.multicodec):lz.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(tC.Uw.LightPush)&&(this.lightPush?i.push(this.lightPush.protocol.multicodec):lz.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(tC.Uw.Filter)&&(this.filter?i.push(this.filter.protocol.multicodec):lz.error("Filter codec not included in dial codec: protocol not mounted locally")),lz.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,i)}async start(){await this.libp2p.start()}async stop(){this.connectionManager.stop(),await this.libp2p.stop()}async subscribeToContentTopic(e,t,r){return(await lq(e,r,{waku:this,peer:t})).subscription}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}getLocalMultiaddrWithID(){let e=this.libp2p.getMultiaddrs().find(e=>e.toString().match(/127\.0\.0\.1/));if(!e||""===e.toString())throw"Not listening on localhost";return e+"/p2p/"+this.libp2p.peerId.toString()}}var lG=r(18976);let lW={lightPush:1,filter:1,store:1};async function lY(e,t,r,n){r?.hideWebSocketInfo||(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));let i=e?{metadata:t=>new t4(e,t)}:{};return lk({connectionManager:{minConnections:1},transports:[function(e={}){return t=>new s2(t,e)}({filter:s1})],streamMuxers:[function(e={}){return t=>new sx(t,e)}()],connectionEncryption:[function(e={}){return t=>new nX(t,e)}()],...r,services:{identify:function(e={}){return t=>new sf(t,e)}({agentVersion:n??"js-waku"}),ping:function(e={}){return t=>new sF(t,e)}(),...i,...t?{pubsub:t}:{},...r?.services}})}async function lQ(e){var t,r;let n=e.shardInfo?(0,ts.Ao)(e.shardInfo):void 0;e.pubsubTopics=n?.pubsubTopics??e.pubsubTopics??[tC.nf];let i=e?.libp2p??{},s=i.peerDiscovery??[];return e?.defaultBootstrap&&s.push(...(t=e.pubsubTopics,[(0,lG.Lk)([lG.Qy.SANDBOX],lW),(0,lG.C0)(),(0,lG.PZ)(t)])),e?.bootstrapPeers&&s.push((r={list:e.bootstrapPeers},e=>new i_(e,r))),i.peerDiscovery=s,await lY(n?.shardInfo,function(e={}){return t=>{let r=new oC(t,e={...e,msgIdFn:({data:e})=>(0,rj.J)(e),globalSignaturePolicy:eF.StrictNoSign,fallbackToFloodsub:!1});return r.multicodecs=oR,r}}(e),i,e?.userAgent)}},48215:function(e,t,r){"use strict";r.d(t,{Md:function(){return a},ci:function(){return o},iY:function(){return l},nr:function(){return s},zo:function(){return c}});var n=r(60565),i=r(12528);function s(e){if("string"==typeof e){let t=e.replace(/^0x/i,"");return(0,n.m)(t.toLowerCase(),"base16")}return e}let o=e=>(0,i.B)(e,"base16"),a=e=>(0,i.B)(e,"utf8"),l=e=>(0,n.m)(e,"utf8");function c(e,t){let r=new Uint8Array(t??e.reduce((e,t)=>e+t.length,0)),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}},98676:function(e,t,r){"use strict";r.d(t,{I:function(){return n},k:function(){return i}});let n=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");let t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){let r=Math.floor(e/8)+2,i=7-e%8;t.getUint8(r)&1<=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(s))}}return{clusterId:r,shards:n}},i=e=>{let{clusterId:t,shards:r}=e,n=new ArrayBuffer(r.length>=64?130:3+2*r.length),i=new DataView(n);if(i.setUint16(0,t),r.length>=64)for(let e of r){let t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<{let r=t.get(e.contentTopic);r||(t.set(e.contentTopic,[]),r=t.get(e.contentTopic)),r.push(e)}),t}async function s(e,t,r){let n;let i=r?.iteratorDelay??60,s=[];n=await e.subscribe(t,e=>{s.push(e)});let o=Number.isInteger(r?.timeoutMs),a=r?.timeoutMs??0,l=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-l>=a)return;await function(e){return new Promise(t=>{setTimeout(t,e)})}(i);let e=s.shift();if(!n&&0===s.length)return e;(e||!n)&&(yield e)}}(),async stop(){n&&(await n(),n=void 0)}}}async function o(e,t){let r=await e.toWire(t);return!!r&&a(r)}r.d(t,{Yd:function(){return I},L3:function(){return m},Ix:function(){return w.I},IY:function(){return y},kL:function(){return w.k},Qu:function(){return f},Ao:function(){return b},Yl:function(){return E},p3:function(){return i},$K:function(){return n},eh:function(){return o},qc:function(){return a},Tf:function(){return p},IC:function(){return v},yf:function(){return d},B2:function(){return s}});let a=e=>e.length/1048576<=1;var l=r(65530),c=r(75354),u=r(48215);let h=e=>{if(void 0===e.shard)throw Error("Invalid shard");return`/waku/2/rs/${e.clusterId??c.eZ}/${e.shard}`},d=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map(t=>m(t,e.clusterId))));if("shards"in e){if(void 0===e.shards)throw Error("Invalid shard");return Array.from(new Set(e.shards.map(t=>`/waku/2/rs/${e.clusterId??c.eZ}/${t}`)))}if("application"in e&&"version"in e)return[m(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw Error("Missing required configuration in shard parameters")},p=e=>{let t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");let r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function f(e,t){if(!t.includes(e))throw Error(`Pubsub topic ${e} has not been configured on this instance. Configured topics are: ${t}. Please update your configuration by passing in the topic during Waku node instantiation.`)}function g(e,t=8){let{application:r,version:n}=function(e){let t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid");let r=0;if(6==t.length){if(isNaN(r=parseInt(t[1])))throw Error("Invalid generation field in content topic");if(r>0)throw Error("Generation greater than 0 is not supported")}let n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty");if(0==n[1].length)throw Error("Version field cannot be empty");if(0==n[2].length)throw Error("Topic name field cannot be empty");if(0==n[3].length)throw Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e);return Number(new DataView((0,l.J)((0,u.zo)([(0,u.iY)(r),(0,u.iY)(n)])).buffer.slice(-8)).getBigUint64(0,!1)%BigInt(t))}function m(e,t=c.eZ,r=8){if(!e)throw Error("Content topic must be specified");let n=g(e,r);return`/waku/2/rs/${t}/${n}`}function y(e,t){return"string"==typeof t?t:t?.shard!==void 0?h(t):m(e,t?.clusterId??c.eZ)}let b=e=>{let t=e.clusterId??c.eZ,r="shards"in e?e.shards:[],n="contentTopics"in e?e.contentTopics:[],[i,s]="application"in e&&"version"in e?[e.application,e.version]:[void 0,void 0],o=r&&r.length>0,a=n&&n.length>0,l=i&&s;if(o)return{shardingParams:{clusterId:t,shards:r},shardInfo:{clusterId:t,shards:r},pubsubTopics:d({clusterId:t,shards:r})};if(a){let e=Array.from(new Set(n.map(e=>m(e,t)))),r=Array.from(new Set(n.map(e=>g(e))));return{shardingParams:{clusterId:t,contentTopics:n},shardInfo:{clusterId:t,shards:r},pubsubTopics:e}}if(l){let e=m(`/${i}/${s}/default/default`,t);return{shardingParams:{clusterId:t,application:i,version:s},shardInfo:{clusterId:t,shards:[p(e).shard]},pubsubTopics:[e]}}throw Error("Missing minimum required configuration options for static sharding or autosharding.")};function v(e,t,r){let n=e.get(t);void 0===n&&(e.set(t,new Set),n=e.get(t)),n.add(r)}var w=r(98676);function E(e){let t=e.find(e=>e.toString().includes("ws")||e.toString().includes("wss"));if(!t)throw Error("No ws multiaddr found in the given addresses");return t}var S=r(55022);let A="waku";class I{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${A}:${e}:${t}`:`${A}:${e}`}constructor(e){this._info=S(I.createDebugNamespace("info",e)),this._warn=S(I.createDebugNamespace("warn",e)),this._error=S(I.createDebugNamespace("error",e))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(0,this[e])(...t)}}},85419:function(e,t,r){"use strict";r.d(t,{RB:function(){return o},_4:function(){return a},s_:function(){return l},tf:function(){return s}});var n=r(48215),i=r(98676);async function s(e,t){return 0===t.length?[]:(await Promise.all(t.map(async t=>{try{let r=(await e.get(t.id)).metadata.get("ping");if(!r)return{peer:t,ping:1/0};let i=Number((0,n.Md)(r));return{peer:t,ping:i}}catch(e){return{peer:t,ping:1/0}}}))).filter(e=>null!==e).sort((e,t)=>e.ping-t.ping).map(e=>e.peer)}async function o(e,t){let r=[];return await e.forEach(e=>{for(let n=0;n"open"===e.status).map(async e=>{let s=await t.get(e.remotePeer);if(r.some(e=>s.protocols.includes(e))){if(!n)return s;{let e=s.metadata.get("shardInfo"),t=e&&(0,i.I)(e);if(t&&n.clusterId===t.clusterId)return s}}return null});return(await Promise.all(s)).filter(e=>null!==e)}function l(e){let t;if(e.length)return 1===e.length?e[0]:(e.forEach(e=>{"open"===e.status&&(t?e.timeline.open>t.timeline.open&&(t=e):t=e)}),t)}},83431:function(e,t){"use strict";t.Z=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{let t=[];for await(let r of e)t.push(r);return t})();let t=[];for(let r of e)t.push(r);return t}},21679:function(e,t,r){"use strict";r.d(t,{J:function(){return p},c:function(){return u}});var n,i,s=r(17954),o=r(54164),a=r(1514);function l(e){return null!=e[Symbol.asyncIterator]}let c=e=>{let t=s.P$(e),r=(0,a.E)(t);return s.cv(e,r),c.bytes=t,r};function u(e,t){let r=(t=t??{}).lengthEncoder??c;function*n(e){let t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return l(e)?async function*(){for await(let t of e)yield*n(t)}():function*(){for(let t of e)yield*n(t)}()}c.bytes=0,u.single=(e,t)=>{let r=(t=t??{}).lengthEncoder??c;return new o.H(r(e.byteLength),e)};var h=r(15862);(n=i||(i={}))[n.LENGTH=0]="LENGTH",n[n.DATA=1]="DATA";let d=e=>{let t=s.Jx(e);return d.bytes=s.P$(t),t};function p(e,t){let r=new o.H,n=i.LENGTH,s=-1,a=t?.lengthDecoder??d,c=t?.maxLengthLength??8,u=t?.maxDataLength??4194304;function*p(){for(;r.byteLength>0;){if(n===i.LENGTH)try{if((s=a(r))<0)throw h(Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>u)throw h(Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let e=a.bytes;r.consume(e),t?.onLength!=null&&t.onLength(s),n=i.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>c)throw h(Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw e}if(n===i.DATA){if(r.byteLength0)throw h(Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let t of e)r.append(t),yield*p();if(r.byteLength>0)throw h(Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}d.bytes=0,p.fromReader=(e,t)=>{let r=1;return p(async function*(){for(;;)try{let{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength:e=>{r=e}})}},10637:function(e,t,r){"use strict";var n=r(35605);t.Z=function(...e){let t=[];for(let r of e)null!=r[Symbol.asyncIterator]||t.push(r);return t.length===e.length?function*(){for(let e of t)yield*e}():async function*(){let t=(0,n.dT)({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async e=>{for await(let r of e)t.push(r)})),t.end()}catch(e){t.end(e)}}),yield*t}()}},37804:function(e,t,r){"use strict";r.d(t,{z:function(){return s}});var n=r(35605),i=r(10637);function s(e,...t){if(null==e)throw Error("Empty pipeline");if(c(e)){let t=e;e=()=>t.source}else if(l(e)||a(e)){let t=e;e=()=>t}let r=[e,...t];if(r.length>1&&c(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e{let t;for(;e.length>0;)t=e.shift()(t);return t},a=e=>e?.[Symbol.asyncIterator]!=null,l=e=>e?.[Symbol.iterator]!=null,c=e=>null!=e&&null!=e.sink&&null!=e.source,u=e=>t=>{let r=e.sink(t);if(r?.then!=null){let t;let s=(0,n.dT)({objectMode:!0});r.then(()=>{s.end()},e=>{s.end(e)});let o=e.source;if(a(o))t=async function*(){yield*o,s.end()};else if(l(o))t=function*(){yield*o,s.end()};else throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");return(0,i.Z)(s,t())}return e.source}},35605:function(e,t,r){"use strict";r.d(t,{dT:function(){return a}});var n=r(60117);class i{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!=0)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class s{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new i(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 i(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){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()}}class o extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function a(e={}){return function(e,t){let r,i,a;let l=(t=t??{}).onEnd,c=new s,u=(0,n.Z)(),h=e=>null!=i?i(e):(c.push(e),r),d=e=>(c=new s,null!=i)?i({error:e}):(c.push({error:e}),r),p=e=>{if(a)return r;if(t?.objectMode!==!0&&e?.byteLength==null)throw Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:e})},f=e=>a?r:(a=!0,null!=e?d(e):h({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{if(!c.isEmpty())return e(c);if(a)return{done:!0};return await new Promise((t,n)=>{i=s=>{i=null,c.push(s);try{t(e(c))}catch(e){n(e)}return r}})}finally{c.isEmpty()&&queueMicrotask(()=>{u.resolve(),u=(0,n.Z)()})}},return:()=>(c=new s,f(),{done:!0}),throw:e=>(f(e),{done:!0}),push:p,end:f,get readableLength(){return c.size},onEmpty:async e=>{let t,r;let n=e?.signal;if(n?.throwIfAborted(),!c.isEmpty()){null!=n&&(t=new Promise((e,t)=>{r=()=>{t(new o)},n.addEventListener("abort",r)}));try{await Promise.race([u.promise,t])}finally{null!=r&&null!=n&&n?.removeEventListener("abort",r)}}}},null==l)return r;let g=r;return r={[Symbol.asyncIterator](){return this},next:()=>g.next(),throw:e=>(g.throw(e),null!=l&&(l(e),l=void 0),{done:!0}),return:()=>(g.return(),null!=l&&(l(),l=void 0),{done:!0}),push:p,end:e=>(g.end(e),null!=l&&(l(e),l=void 0),r),get readableLength(){return g.readableLength},onEmpty:e=>g.onEmpty(e)}}(e=>{let t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}},e)}},6240:function(e,t,r){"use strict";r.d(t,{kU:function(){return h},Dp:function(){return u},ET:function(){return d}});var n=r(21786),i=function(e,t){if(e.length>=255)throw TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=s-1;(0!==u||h>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw Error("Non-zero carry");i=h,t++}if(" "!==e[t]){for(var p=s-i;p!==s&&0===o[p];)p++;for(var f=new Uint8Array(n+(s-p)),g=n;p!==s;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,s=t.length;i!==s&&0===t[i];)i++,r++;for(var o=(s-i)*u+1>>>0,c=new Uint8Array(o);i!==s;){for(var h=t[i],d=0,p=o-1;(0!==h||d>>0,c[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw Error("Non-zero carry");n=d,i++}for(var f=o-n;f!==o&&0===c[f];)f++;for(var g=l.repeat(r);f(0,n.oQ)(o(e))})}function d({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return u({prefix:t,name:e,encode:e=>(function(e,t,r){let n="="===t[t.length-1],i=(1<r;)o-=r,s+=t[i&a>>o];if(0!==o&&(s+=t[i&a<(function(e,t,r,n){let i={};for(let e=0;e=8&&(a-=8,o[c++]=255&l>>a)}if(a>=r||(255&l<<8-a)!=0)throw SyntaxError("Unexpected end of data");return o})(t,n,r,e)})}},60522:function(e,t,r){"use strict";r.r(t),r.d(t,{base32:function(){return i},base32hex:function(){return l},base32hexpad:function(){return u},base32hexpadupper:function(){return h},base32hexupper:function(){return c},base32pad:function(){return o},base32padupper:function(){return a},base32upper:function(){return s},base32z:function(){return d}});var n=r(6240);let i=(0,n.ET)({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),s=(0,n.ET)({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o=(0,n.ET)({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a=(0,n.ET)({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),l=(0,n.ET)({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),c=(0,n.ET)({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),u=(0,n.ET)({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),h=(0,n.ET)({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),d=(0,n.ET)({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})},75360:function(e,t,r){"use strict";r.r(t),r.d(t,{base58btc:function(){return i},base58flickr:function(){return s}});var n=r(6240);let i=(0,n.kU)({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),s=(0,n.kU)({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})},84018:function(e,t,r){"use strict";r.r(t),r.d(t,{base64:function(){return i},base64pad:function(){return s},base64url:function(){return o},base64urlpad:function(){return a}});var n=r(6240);let i=(0,n.ET)({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),s=(0,n.ET)({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),o=(0,n.ET)({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),a=(0,n.ET)({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})},74006:function(e,t,r){"use strict";r.d(t,{gh:function(){return V}});var n={};r.r(n),r.d(n,{base10:function(){return p}});var i={};r.r(i),r.d(i,{base16:function(){return f},base16upper:function(){return g}});var s={};r.r(s),r.d(s,{base2:function(){return m}});var o={};r.r(o),r.d(o,{base256emoji:function(){return w}});var a={};r.r(a),r.d(a,{base36:function(){return S},base36upper:function(){return A}});var l={};r.r(l),r.d(l,{base8:function(){return T}});var c={};r.r(c),r.d(c,{identity:function(){return R}});var u={};r.r(u),r.d(u,{code:function(){return B},decode:function(){return L},encode:function(){return N},name:function(){return D}});var h={};r.r(h),r.d(h,{code:function(){return O},decode:function(){return U},encode:function(){return M},name:function(){return x}});var d=r(6240);let p=(0,d.kU)({prefix:"9",name:"base10",alphabet:"0123456789"}),f=(0,d.ET)({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),g=(0,d.ET)({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),m=(0,d.ET)({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),y=Array.from("\uD83D\uDE80\uD83E\uDE90☄\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09☀\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02❤\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09☺\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E✌✨\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D❣\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33✋\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13⭐✅\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6✔\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90☹\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20☝\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B⚽\uD83E\uDD19☕\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81⚡\uD83C\uDF1E\uD83C\uDF88❌✊\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C✈\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74▶➡❓\uD83D\uDC8E\uD83D\uDCB8⬇\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A⚠\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37☎\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51❄\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42"),b=y.reduce((e,t,r)=>(e[r]=t,e),[]),v=y.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]),w=(0,d.Dp)({prefix:"\uD83D\uDE80",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+=b[t],"")},decode:function(e){let t=[];for(let r of e){let e=v[r.codePointAt(0)];if(void 0===e)throw Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var E=r(60522);let S=(0,d.kU)({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),A=(0,d.kU)({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var I=r(75360),_=r(84018);let T=(0,d.ET)({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var C=r(21786);let R=(0,d.Dp)({prefix:"\0",name:"identity",encode:e=>(0,C.BB)(e),decode:e=>(0,C.mL)(e)}),k=new TextEncoder,P=new TextDecoder,D="json",B=512;function N(e){return k.encode(JSON.stringify(e))}function L(e){return JSON.parse(P.decode(e))}let x="raw",O=85;function M(e){return(0,C.oQ)(e)}function U(e){return(0,C.oQ)(e)}var F=r(60575),K=r(30024);r(45193),r(2780),r(40291),r(83695);let V={...c,...s,...l,...n,...i,...E,...a,...I,..._,...o};({...K,...F})},21786:function(e,t,r){"use strict";function n(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{let[r,n]=a.Jx(e.subarray(t));return t+=n,r},n=r(),i=d;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw RangeError(`Invalid CID version ${n}`);let s=t,o=r(),l=r(),c=t+l;return{version:n,codec:i,multihashCode:o,digestSize:l,multihashSize:c-s,size:c}}static parse(e,t){let[r,s]=function(e,t){switch(e[0]){case"Q":{let r=t??i.base58btc;return[i.base58btc.prefix,r.decode(`${i.base58btc.prefix}${e}`)]}case i.base58btc.prefix:{let r=t??i.base58btc;return[i.base58btc.prefix,r.decode(e)]}case n.base32.prefix:{let r=t??n.base32;return[n.base32.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),o=h.decode(s);if(0===o.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return u(o).set(r,e),o}}let d=112,p=18;function f(e,t,r){let n=a.P$(e),i=n+a.P$(t),s=new Uint8Array(i+r.byteLength);return a.mL(e,s,0),a.mL(t,s,n),s.set(r,i),s}let g=Symbol.for("@ipld/js-cid/CID")},2780:function(e,t,r){"use strict";r.d(t,{Jx:function(){return o},Ue:function(){return s},fS:function(){return a},zZ:function(){return l}});var n=r(21786),i=r(83695);function s(e,t){let r=t.byteLength,n=i.P$(e),s=n+i.P$(r),o=new Uint8Array(s+r);return i.mL(e,o,0),i.mL(r,o,n),o.set(t,s),new l(e,r,t,o)}function o(e){let t=(0,n.oQ)(e),[r,s]=i.Jx(t),[o,a]=i.Jx(t.subarray(s)),c=t.subarray(s+a);if(c.byteLength!==o)throw Error("Incorrect length");return new l(r,o,c,t)}function a(e,t){return e===t||e.code===t.code&&e.size===t.size&&t.bytes instanceof Uint8Array&&(0,n.fS)(e.bytes,t.bytes)}class l{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}},40291:function(e,t,r){"use strict";r.d(t,{D:function(){return i}});var n=r(2780);function i({name:e,code:t,encode:r}){return new s(e,t,r)}class s{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?n.Ue(this.code,t):t.then(e=>n.Ue(this.code,e))}throw Error("Unknown type, must be binary type")}}},60575:function(e,t,r){"use strict";r.r(t),r.d(t,{identity:function(){return o}});var n=r(21786),i=r(2780);let s=n.oQ,o={code:0,name:"identity",encode:s,digest:function(e){return i.Ue(0,s(e))}}},30024:function(e,t,r){"use strict";r.r(t),r.d(t,{sha256:function(){return s},sha512:function(){return o}});var n=r(40291);function i(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}let s=(0,n.D)({name:"sha2-256",code:18,encode:i("SHA-256")}),o=(0,n.D)({name:"sha2-512",code:19,encode:i("SHA-512")})},83695:function(e,t,r){"use strict";r.d(t,{Jx:function(){return s},mL:function(){return o},P$:function(){return a}});var n=function e(t,r,n){r=r||[];for(var i=n=n||0;t>=2147483648;)r[n++]=255&t|128,t/=128;for(;-128&t;)r[n++]=255&t|128,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},i=function e(t,r){var n,i=0,r=r||0,s=0,o=r,a=t.length;do{if(o>=a)throw e.bytes=0,RangeError("Could not decode varint");n=t[o++],i+=s<28?(127&n)<=128);return e.bytes=o-r,i};function s(e,t=0){return[i(e,t),i.bytes]}function o(e,t,r=0){return n(e,t,r),t}function a(e){return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<0x7fffffffffffffff?9:10}},60117:function(e,t,r){"use strict";function n(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}r.d(t,{Z:function(){return n}})},47971:function(e,t,r){"use strict";r.d(t,{sv:function(){return V},C6:function(){return E},LE:function(){return M},Ji:function(){return F},yw:function(){return K}});var n,i,s=r(17954);let o=new Float32Array([-0]),a=new Uint8Array(o.buffer);function l(e,t,r){o[0]=e,t[r]=a[0],t[r+1]=a[1],t[r+2]=a[2],t[r+3]=a[3]}let c=new Float64Array([-0]),u=new Uint8Array(c.buffer);function h(e,t,r){c[0]=e,t[r]=u[0],t[r+1]=u[1],t[r+2]=u[2],t[r+3]=u[3],t[r+4]=u[4],t[r+5]=u[5],t[r+6]=u[6],t[r+7]=u[7]}let d=BigInt(Number.MAX_SAFE_INTEGER),p=BigInt(Number.MIN_SAFE_INTEGER);class f{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){let e=~this.lo+1>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){let e=~this.lo+1>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<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=-(1&this.lo);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,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return g;if(ep)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>m&&(n=0n,++r>m&&(r=0n))),new f(Number(n),Number(r))}static fromNumber(e){if(0===e)return g;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new f(r,n)}static from(e){return"number"==typeof e?f.fromNumber(e):"bigint"==typeof e?f.fromBigInt(e):"string"==typeof e?f.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new f(e.low>>>0,e.high>>>0):g}}let g=new f(0,0);g.toBigInt=function(){return 0n},g.zzEncode=g.zzDecode=function(){return this},g.length=function(){return 1};let m=4294967296n;function y(e,t,r){let n,i;let s=r;for(let s=0;s>6|192:((64512&n)==55296&&(64512&(i=e.charCodeAt(s+1)))==56320?(n=65536+((1023&n)<<10)+(1023&i),++s,t[r++]=n>>18|240,t[r++]=n>>12&63|128):t[r++]=n>>12|224,t[r++]=n>>6&63|128),t[r++]=63&n|128);return r-s}function b(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function v(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class w{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=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,b(this,10);return e}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)|0}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw b(this,4);return v(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw b(this,4);return 0|v(this.buf,this.pos+=4)}float(){var e,t;if(this.pos+4>this.len)throw b(this,4);let r=(e=this.buf,t=this.pos,a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],a[3]=e[t+3],o[0]);return this.pos+=4,r}double(){var e,t;if(this.pos+8>this.len)throw b(this,4);let r=(e=this.buf,t=this.pos,u[0]=e[t],u[1]=e[t+1],u[2]=e[t+2],u[3]=e[t+3],u[4]=e[t+4],u[5]=e[t+5],u[6]=e[t+6],u[7]=e[t+7],c[0]);return this.pos+=8,r}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw b(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return function(e,t,r){let n,i;if(r-t<1)return"";let s=[],o=0;for(;t191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw b(this,e);this.pos+=e}else do if(this.pos>=this.len)throw b(this);while((128&this.buf[this.pos++])!=0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)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 f(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw b(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw b(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw b(this,8);return new f(v(this.buf,this.pos+=4),v(this.buf,this.pos+=4))}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=(0,s.CJ)(this.buf,this.pos);return this.pos+=(0,s.P$)(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 E(e,t,r){let n=new w(e instanceof Uint8Array?e:e.subarray());return t.decode(n,void 0,r)}var S=r(1514),A=r(60565);class I{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function _(){}class T{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}let C=function(e){let t;let r=(void 0)??8192,n=r>>>1,i=r;return function(e){if(e<1||e>n)return(0,S.E)(e);i+e>r&&(t=(0,S.E)(r),i=0);let s=t.subarray(i,i+=e);return(7&i)!=0&&(i=(7|i)+1),s}}();class R{len;head;tail;states;constructor(){this.len=0,this.head=new I(_,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new I(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new D((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(B,10,f.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=f.fromBigInt(e);return this._push(B,t.length(),t)}uint64Number(e){return this._push(s.lN,(0,s.P$)(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=f.fromBigInt(e).zzEncode();return this._push(B,t.length(),t)}sint64Number(e){let t=f.fromNumber(e).zzEncode();return this._push(B,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(k,1,e?1:0)}fixed32(e){return this._push(N,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=f.fromBigInt(e);return this._push(N,4,t.lo)._push(N,4,t.hi)}fixed64Number(e){let t=f.fromNumber(e);return this._push(N,4,t.lo)._push(N,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(l,4,e)}double(e){return this._push(h,8,e)}bytes(e){let t=e.length>>>0;return 0===t?this._push(k,1,0):this.uint32(t)._push(L,t,e)}string(e){let t=function(e){let t=0,r=0;for(let n=0;n127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class D extends I{next;constructor(e,t){super(P,e,t),this.next=void 0}}function B(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function N(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function L(e,t,r){t.set(e,r)}function x(e,t,r){t.set(e,r)}function O(e,t,r){e.length<40?y(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set((0,A.m)(e),r)}function M(e,t){let r=new R;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function U(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function F(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return U("enum",i.VARINT,function(e,r){let n=t(e);r.int32(n)},function(e){return t(e.int32())})}function K(e,t){return U("message",i.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(R.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(x,t,e),this},R.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(O,t,e),this}),(n=i||(i={}))[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32";class V extends Error{code;constructor(e,t,r){super(e,r),this.code=t}}},17954:function(e,t,r){"use strict";r.d(t,{CJ:function(){return o},Jx:function(){return l},P$:function(){return i},cv:function(){return a},lN:function(){return s}});var n=r(1514);function i(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<268435456)return 4;if(e<34359738368)return 5;if(e<4398046511104)return 6;if(e<562949953421312)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw RangeError("Could not encode varint");return 8}function s(e,t,r=0){switch(i(e)){case 8:t[r++]=255&e|128,e/=128;case 7:t[r++]=255&e|128,e/=128;case 6:t[r++]=255&e|128,e/=128;case 5:t[r++]=255&e|128,e/=128;case 4:t[r++]=255&e|128,e>>>=7;case 3:t[r++]=255&e|128,e>>>=7;case 2:t[r++]=255&e|128,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function o(e,t){let r,n=e[t];if(r=0+(127&n),n<128||(r+=(127&(n=e[t+1]))<<7,n<128)||(r+=(127&(n=e[t+2]))<<14,n<128)||(r+=(127&(n=e[t+3]))<<21,n<128)||(r+=(127&(n=e[t+4]))*268435456,n<128)||(r+=(127&(n=e[t+5]))*34359738368,n<128)||(r+=(127&(n=e[t+6]))*4398046511104,n<128)||(r+=(127&(n=e[t+7]))*562949953421312,n<128))return r;throw RangeError("Could not decode varint")}function a(e,t,r=0){return(null==t&&(t=(0,n.E)(i(e))),t instanceof Uint8Array)?s(e,t,r):function(e,t,r=0){switch(i(e)){case 8:t.set(r++,255&e|128),e/=128;case 7:t.set(r++,255&e|128),e/=128;case 6:t.set(r++,255&e|128),e/=128;case 5:t.set(r++,255&e|128),e/=128;case 4:t.set(r++,255&e|128),e>>>=7;case 3:t.set(r++,255&e|128),e>>>=7;case 2:t.set(r++,255&e|128),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function l(e,t=0){return e instanceof Uint8Array?o(e,t):function(e,t){let r,n=e.get(t);if(r=0+(127&n),n<128||(r+=(127&(n=e.get(t+1)))<<7,n<128)||(r+=(127&(n=e.get(t+2)))<<14,n<128)||(r+=(127&(n=e.get(t+3)))<<21,n<128)||(r+=(127&(n=e.get(t+4)))*268435456,n<128)||(r+=(127&(n=e.get(t+5)))*34359738368,n<128)||(r+=(127&(n=e.get(t+6)))*4398046511104,n<128)||(r+=(127&(n=e.get(t+7)))*562949953421312,n<128))return r;throw RangeError("Could not decode varint")}(e,t)}},54164:function(e,t,r){"use strict";r.d(t,{H:function(){return c},Z:function(){return l}});var n=r(1514),i=r(83508),s=r(38856);let o=Symbol.for("@achingbrain/uint8arraylist");function a(e,t){if(null==t||t<0)throw RangeError("index is out of bounds");let r=0;for(let n of e){let e=r+n.byteLength;if(t0&&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 r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(l(r))t+=r.byteLength,this.bufs.push(...r.bufs);else throw 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 r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(l(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=a(this.bufs,e);return t.buf[t.index]}set(e,t){let r=a(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r0;)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:r,length:n}=this._subList(e,t);return(0,i.z)(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:(0,i.z)(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new c;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let i=0;i=a)continue;let l=e>=o&&eo&&t<=a;if(l&&c){if(e===o&&t===a){r.push(s);break}let n=e-o;r.push(s.subarray(n,n+(t-e)));break}if(l){if(0===e){r.push(s);continue}r.push(s.subarray(e-o));continue}if(c){if(t===a){r.push(s);break}r.push(s.subarray(0,t-o));break}r.push(s)}return{bufs:r,length:t-e}}indexOf(e,t=0){let r;if(!l(e)&&!(e instanceof Uint8Array))throw TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(t??0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;let i=n.byteLength;if(0===i)throw TypeError("search must be at least 1 byte long");let s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e=0;t--){let i=this.get(e+t);if(n[t]!==i){r=Math.max(1,t-s[i]);break}}if(0===r)return e}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 r=(0,n.E)(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let i=(0,n.u)(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,r),this.write(i,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let i=(0,n.u)(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,r),this.write(i,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let i=(0,n.u)(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,r),this.write(i,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 r=(0,n.E)(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let i=(0,n.u)(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,r),this.write(i,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let i=(0,n.u)(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,r),this.write(i,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let i=(0,n.u)(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,r),this.write(i,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let i=(0,n.u)(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,r),this.write(i,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let i=(0,n.u)(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,r),this.write(i,e)}equals(e){if(null==e||!(e instanceof c)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;te+t.byteLength,0)),r.length=t,r}}},1514:function(e,t,r){"use strict";function n(e=0){return new Uint8Array(e)}function i(e=0){return new Uint8Array(e)}r.d(t,{E:function(){return i},u:function(){return n}})},83508:function(e,t,r){"use strict";r.d(t,{z:function(){return i}});var n=r(1514);function i(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));let r=(0,n.E)(t),i=0;for(let t of e)r.set(t,i),i+=t.length;return r}},38856:function(e,t,r){"use strict";function n(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),a=s("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=(0,i.E)(e.length);for(let r=0;r