status-im-auto cd1a399000 Updates
2025-01-24 20:33:15 +00:00

3 lines
674 KiB
JavaScript

/*! For license information please see index.js.LICENSE.txt */
(()=>{var __webpack_modules__={8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,o=2,s=!0;o<arguments.length;)r[n++]=arguments[o++];return new Promise((function(o,i){r[n]=function(e){if(s)if(s=!1,e)i(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];o.apply(null,t)}};try{e.apply(t||null,r)}catch(e){s&&(s=!1,i(e))}}))}},8839:(e,t)=>{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),o=new Array(123),s=0;s<64;)o[n[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;r.encode=function(e,t,r){for(var o,s=null,i=[],a=0,c=0;t<r;){var l=e[t++];switch(c){case 0:i[a++]=n[l>>2],o=(3&l)<<4,c=1;break;case 1:i[a++]=n[o|l>>4],o=(15&l)<<2,c=2;break;case 2:i[a++]=n[o|l>>6],i[a++]=n[63&l],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),a=0)}return c&&(i[a++]=n[o],i[a++]=61,1===c&&(i[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,i.slice(0,a))),s.join("")):String.fromCharCode.apply(String,i.slice(0,a))};var i="invalid encoding";r.decode=function(e,t,r){for(var n,s=r,a=0,c=0;c<e.length;){var l=e.charCodeAt(c++);if(61===l&&a>1)break;if(void 0===(l=o[l]))throw Error(i);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(i);return r-s},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},8561:e=>{"use strict";function t(e,r){"string"==typeof e&&(r=e,e=void 0);var n=[];function o(e){if("string"!=typeof e){var r=s();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var i=Object.keys(e),a=new Array(i.length+1),c=new Array(i.length),l=0;l<i.length;)a[l]=i[l],c[l]=e[i[l++]];return a[l]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),h=0;h<u.length;)u[h]=arguments[++h];if(h=0,e=e.replace(/%([%dfijs])/g,(function(e,t){var r=u[h++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"})),h!==u.length)throw Error("parameter count mismatch");return n.push(e),o}function s(t){return"function "+(t||r||"")+"("+(e&&e.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return o.toString=s,o}e.exports=t,t.verbose=!1},4358:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n<r.length;)r[n].fn===t?r.splice(n,1):++n;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],n=1;n<arguments.length;)r.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,r)}return this}},5212:(e,t,r)=>{"use strict";e.exports=s;var n=r(8045),o=r(4153)("fs");function s(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&o&&o.readFile?o.readFile(e,(function(n,o){return n&&"undefined"!=typeof XMLHttpRequest?s.xhr(e,t,r):n?r(n):r(null,t.binary?o:o.toString("utf8"))})):s.xhr(e,t,r):n(s,this,e,t)}s.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var o=0;o<n.responseText.length;++o)e.push(255&n.responseText.charCodeAt(o))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,n.responseText)}},t.binary&&("overrideMimeType"in n&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.responseType="arraybuffer"),n.open("GET",e),n.send()}},9410:e=>{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function o(e,n,o){t[0]=e,n[o]=r[0],n[o+1]=r[1],n[o+2]=r[2],n[o+3]=r[3]}function s(e,n,o){t[0]=e,n[o]=r[3],n[o+1]=r[2],n[o+2]=r[1],n[o+3]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?o:s,e.writeFloatBE=n?s:o,e.readFloatLE=n?i:a,e.readFloatBE=n?a:i}():function(){function t(e,t,r,n){var o=t<0?1:0;if(o&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((o<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((o<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((o<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,r,n)}}function i(e,t,r){var n=e(t,r),o=2*(n>>31)+1,s=n>>>23&255,i=8388607&n;return 255===s?i?NaN:o*(1/0):0===s?1401298464324817e-60*o*i:o*Math.pow(2,s-150)*(i+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=i.bind(null,o),e.readFloatBE=i.bind(null,s)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function o(e,n,o){t[0]=e,n[o]=r[0],n[o+1]=r[1],n[o+2]=r[2],n[o+3]=r[3],n[o+4]=r[4],n[o+5]=r[5],n[o+6]=r[6],n[o+7]=r[7]}function s(e,n,o){t[0]=e,n[o]=r[7],n[o+1]=r[6],n[o+2]=r[5],n[o+3]=r[4],n[o+4]=r[3],n[o+5]=r[2],n[o+6]=r[1],n[o+7]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?o:s,e.writeDoubleBE=n?s:o,e.readDoubleLE=n?i:a,e.readDoubleBE=n?a:i}():function(){function t(e,t,r,n,o,s){var i=n<0?1:0;if(i&&(n=-n),0===n)e(0,o,s+t),e(1/n>0?0:2147483648,o,s+r);else if(isNaN(n))e(0,o,s+t),e(2146959360,o,s+r);else if(n>17976931348623157e292)e(0,o,s+t),e((i<<31|2146435072)>>>0,o,s+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,o,s+t),e((i<<31|a/4294967296)>>>0,o,s+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,o,s+t),e((i<<31|c+1023<<20|1048576*a&1048575)>>>0,o,s+r)}}}function i(e,t,r,n,o){var s=e(n,o+t),i=e(n,o+r),a=2*(i>>31)+1,c=i>>>20&2047,l=4294967296*(1048575&i)+s;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=i.bind(null,o,0,4),e.readDoubleBE=i.bind(null,s,4,0)}(),e}function r(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 n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function o(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},9207:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},o=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),o="";r&&(o=t.shift()+"/");for(var s=0;s<t.length;)".."===t[s]?s>0&&".."!==t[s-1]?t.splice(--s,2):r?t.splice(s,1):++s:"."===t[s]?t.splice(s,1):++s;return o+t.join("/")};r.resolve=function(e,t,r){return r||(t=o(t)),n(t)?t:(r||(e=o(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?o(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,o=n>>>1,s=null,i=n;return function(r){if(r<1||r>o)return e(r);i+r>n&&(s=e(n),i=0);var a=t.call(s,i,i+=r);return 7&i&&(i=1+(7|i)),a}}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n<e.length;++n)(r=e.charCodeAt(n))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t},r.read=function(e,t,r){if(r-t<1)return"";for(var n,o=null,s=[],i=0;t<r;)(n=e[t++])<128?s[i++]=n:n>191&&n<224?s[i++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[i++]=55296+(n>>10),s[i++]=56320+(1023&n)):s[i++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o?(i&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))},r.write=function(e,t,r){for(var n,o,s=r,i=0;i<e.length;++i)(n=e.charCodeAt(i))<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(o=e.charCodeAt(i+1)))?(n=65536+((1023&n)<<10)+(1023&o),++i,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-s}},7833:(e,t,r)=>{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;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,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&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,o,s,i=null;function a(...e){if(!a.enabled)return;const n=a,o=Number(new Date),s=o-(r||o);n.diff=s,n.prev=r,n.curr=o,r=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,o)=>{if("%%"===r)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];r=s.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,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!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function o(e,t){let r=0,n=0,o=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(o=n,s=r,n++):(r++,n++);else{if(-1===o)return!1;n=o+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(" ",",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(o(e,r))return!1;for(const r of t.names)if(o(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},544:(e,t,r)=>{"use strict";const n=r(9939);t.PP=n.EventIterator,n.EventIterator},9939:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=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){this.isStopped=!0,this.remove();for(const e of 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(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const 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}={}){const o=new r;o.highWaterMark=t,o.lowWaterMark=n,o.removeCallback=e({push:e=>o.push(e),stop:()=>o.stop(),fail:e=>o.fail(e),on:(e,t)=>{o.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,i){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new o(n,s||e,i),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function i(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,o=[];if(0===this._eventsCount)return o;for(n in e=this._events)t.call(e,n)&&o.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,o,s,i){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,o),!0;case 5:return u.fn.call(u.context,t,n,o,s),!0;case 6:return u.fn.call(u.context,t,n,o,s,i),!0}for(l=1,c=new Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,o);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,o){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return i(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||n&&a.context!==n||i(this,s);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||o&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[s]=1===l.length?l[0]:l:i(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&i(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a},194: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 o(o,s){r[o]=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])?(o(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:o(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=global);var o=!t.HI_BASE32_NO_COMMON_JS&&e.exports,s=r.amdO,i="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},c=[0,0,0,0,0,0,0,0],l=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new 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){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,o,s,i,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],c=a[e.charAt(p++)],l=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4),u[h++]=255&(o<<4|s>>>1),u[h++]=255&(s<<7|i<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4),u[h++]=255&(o<<4|s>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4),u[h++]=255&(o<<4|s>>>1),u[h++]=255&(s<<7|i<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",o=e.length,s=0,i=0;s<o;)if((t=e[s++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,i=1):t<=239?(r=15&t,i=2):t<=247?(r=7&t,i=3):l(s,n);for(var a=0;a<i;++a)((t=e[s++])<128||t>191)&&l(s,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(s,n),r>1114111&&l(s,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(u(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,o,s,i,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g<m;)r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],d=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))+String.fromCharCode(255&(s<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))):5===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))+String.fromCharCode(255&(s<<4|i>>>1))):7===y&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))+String.fromCharCode(255&(s<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,o,s,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],n=e[l++],o=e[l++],s=e[l++],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[31&(o<<3|s>>>5)]+i[31&s];var h=c-u;return 1===h?(t=e[l],a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],o=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[o<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,o,s,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),o=e.charCodeAt(l++),s=e.charCodeAt(l++),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[31&(o<<3|s>>>5)]+i[31&s];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),o=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[o<<3&31]+"="),a}(e):function(e){var t,r,n,o,s,a,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=p;d<f&&l<5;++d)(a=e.charCodeAt(d))<128?c[l++]=a:a<2048?(c[l++]=192|a>>6,c[l++]=128|63&a):a<55296||a>=57344?(c[l++]=224|a>>12,c[l++]=128|a>>6&63,c[l++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=c[0],l>4?(r=c[1],n=c[2],o=c[3],s=c[4],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[31&(o<<3|s>>>5)]+i[31&s]):1===l?h+=i[t>>>3]+i[t<<2&31]+"======":2===l?(r=c[1],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):(r=c[1],n=c[2],o=c[3],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[o<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,o?e.exports=d:(t.base32=d,s&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4866:e=>{e.exports=function(){return"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0}},6368:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},1176:(e,t,r)=>{var n;!function(){"use strict";var o="input is invalid type",s="object"==typeof window,i=s?window:{};i.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"==typeof self;!i.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?i=global:a&&(i=self);for(var c=!i.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!i.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[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],g=[224,256,384,512],m=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=i.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(o);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(o);return[e,!1]},S=function(e){return 0===E(e)[0].length},A=function(e){for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},k=function(e,t,r){return function(n){return new F(e,t,e).update(n)[r]()}},C=function(e,t,r){return function(n,o){return new F(e,t,o).update(n)[r]()}},I=function(e,t,r){return function(t,n,o,s){return P["cshake"+e].update(t,n,o,s)[r]()}},x=function(e,t,r){return function(t,n,o,s){return P["kmac"+e].update(t,n,o,s)[r]()}},T=function(e,t,r,n){for(var o=0;o<y.length;++o){var s=y[o];e[s]=t(r,n,s)}return e},_=function(e,t){var r=k(e,t,"hex");return r.create=function(){return new F(e,t,e)},r.update=function(e){return r.create().update(e)},T(r,k,e,t)},N=[{name:"keccak",padding:[1,256,65536,16777216],bits:g,createMethod:_},{name:"sha3",padding:[6,1536,393216,100663296],bits:g,createMethod:_},{name:"shake",padding:[31,7936,2031616,520093696],bits:m,createMethod:function(e,t){var r=C(e,t,"hex");return r.create=function(r){return new F(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},T(r,C,e,t)}},{name:"cshake",padding:d,bits:m,createMethod:function(e,t){var r=b[e],n=I(e,0,"hex");return n.create=function(n,o,s){return S(o)&&S(s)?P["shake"+e].create(n):new F(e,t,n).bytepad([o,s],r)},n.update=function(e,t,r,o){return n.create(t,r,o).update(e)},T(n,I,e,t)}},{name:"kmac",padding:d,bits:m,createMethod:function(e,t){var r=b[e],n=x(e,0,"hex");return n.create=function(n,o,s){return new $(e,t,o).bytepad(["KMAC",s],r).bytepad([n],r)},n.update=function(e,t,r,o){return n.create(e,r,o).update(t)},T(n,x,e,t)}}],P={},L=[],B=0;B<N.length;++B)for(var O=N[B],R=O.bits,D=0;D<R.length;++D){var U=O.name+"_"+R[D];if(L.push(U),P[U]=O.createMethod(R[D],O.padding),"sha3"!==O.name){var M=O.name+R[D];L.push(M),P[M]=P[U]}}function F(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>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 $(e,t,r){F.call(this,e,t,r)}F.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,o=t[1],s=this.blocks,i=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l<a;){if(this.reset)for(this.reset=!1,s[0]=this.block,r=1;r<c+1;++r)s[r]=0;if(o)for(r=this.start;l<a&&r<i;++l)(n=e.charCodeAt(l))<128?s[r>>2]|=n<<p[3&r++]:n<2048?(s[r>>2]|=(192|n>>6)<<p[3&r++],s[r>>2]|=(128|63&n)<<p[3&r++]):n<55296||n>=57344?(s[r>>2]|=(224|n>>12)<<p[3&r++],s[r>>2]|=(128|n>>6&63)<<p[3&r++],s[r>>2]|=(128|63&n)<<p[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++l)),s[r>>2]|=(240|n>>18)<<p[3&r++],s[r>>2]|=(128|n>>12&63)<<p[3&r++],s[r>>2]|=(128|n>>6&63)<<p[3&r++],s[r>>2]|=(128|63&n)<<p[3&r++]);else for(r=this.start;l<a&&r<i;++l)s[r>>2]|=e[l]<<p[3&r++];if(this.lastByteIndex=r,r>=i){for(this.start=r-i,this.block=s[c],r=0;r<c;++r)u[r]^=s[r];q(u),this.reset=!0}else this.start=r}return this},F.prototype.encode=function(e,t){var r=255&e,n=1,o=[r];for(r=255&(e>>=8);r>0;)o.unshift(r),r=255&(e>>=8),++n;return t?o.push(n):o.unshift(n),this.update(o),o.length},F.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,o=e.length;if(r)for(var s=0;s<e.length;++s){var i=e.charCodeAt(s);i<128?n+=1:i<2048?n+=2:i<55296||i>=57344?n+=3:(i=65536+((1023&i)<<10|1023&e.charCodeAt(++s)),n+=4)}else n=o;return n+=this.encode(8*n),this.update(e),n},F.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var o=(t-r%t)%t,s=[];return s.length=o,this.update(s),this},F.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];q(n)}},F.prototype.toString=F.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,o=this.extraBytes,s=0,i=0,a="";i<n;){for(s=0;s<t&&i<n;++s,++i)e=r[s],a+=h[e>>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];i%t==0&&(r=A(r),q(r),s=0)}return o&&(e=r[s],a+=h[e>>4&15]+h[15&e],o>1&&(a+=h[e>>12&15]+h[e>>8&15]),o>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},F.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,o=this.extraBytes,s=0,i=0,a=this.outputBits>>3;e=o?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);i<n;){for(s=0;s<t&&i<n;++s,++i)c[i]=r[s];i%t==0&&(r=A(r),q(r))}return o&&(c[i]=r[s],e=e.slice(0,a)),e},F.prototype.buffer=F.prototype.arrayBuffer,F.prototype.digest=F.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,o=this.outputBlocks,s=this.extraBytes,i=0,a=0,c=[];a<o;){for(i=0;i<r&&a<o;++i,++a)e=a<<2,t=n[i],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=A(n),q(n))}return s&&(e=a<<2,t=n[i],c[e]=255&t,s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c},$.prototype=new F,$.prototype.finalize=function(){return this.encode(this.outputBits,!0),F.prototype.finalize.call(this)};var q=function(e){var t,r,n,o,s,i,a,c,l,u,h,d,p,g,m,y,b,w,v,E,S,A,k,C,I,x,T,_,N,P,L,B,O,R,D,U,M,F,$,q,H,j,V,z,K,G,W,J,X,Y,Z,Q,ee,te,re,ne,oe,se,ie,ae,ce,le,ue;for(n=0;n<48;n+=2)o=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=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],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(i<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|i>>>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=o^(c<<1|l>>>31),r=s^(l<<1|c>>>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=i^(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=c^(d<<1|p>>>31),r=l^(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^(o<<1|s>>>31),r=h^(s<<1|o>>>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,g=e[0],m=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,_=e[20]<<3|e[21]>>>29,N=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,V=e[41]<<18|e[40]>>>14,R=e[2]<<1|e[3]>>>31,D=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,J=e[22]<<10|e[23]>>>22,X=e[23]<<10|e[22]>>>22,P=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,M=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Z=e[35]<<15|e[34]>>>17,B=e[45]<<29|e[44]>>>3,O=e[44]<<29|e[45]>>>3,C=e[6]<<28|e[7]>>>4,I=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,oe=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,z=e[8]<<27|e[9]>>>5,K=e[9]<<27|e[8]>>>5,x=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,ie=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,k=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=C^~x&_,e[11]=I^~T&N,e[20]=R^~U&F,e[21]=D^~M&$,e[30]=z^~G&J,e[31]=K^~W&X,e[40]=te^~ne&se,e[41]=re^~oe&ie,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=x^~_&P,e[13]=T^~N&L,e[22]=U^~F&q,e[23]=M^~$&H,e[32]=G^~J&Y,e[33]=W^~X&Z,e[42]=ne^~se&ae,e[43]=oe^~ie&ce,e[4]=w^~E&A,e[5]=v^~S&k,e[14]=_^~P&B,e[15]=N^~L&O,e[24]=F^~q&j,e[25]=$^~H&V,e[34]=J^~Y&Q,e[35]=X^~Z&ee,e[44]=se^~ae&le,e[45]=ie^~ce&ue,e[6]=E^~A&g,e[7]=S^~k&m,e[16]=P^~B&C,e[17]=L^~O&I,e[26]=q^~j&R,e[27]=H^~V&D,e[36]=Y^~Q&z,e[37]=Z^~ee&K,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=k^~m&b,e[18]=B^~C&x,e[19]=O^~I&T,e[28]=j^~R&U,e[29]=V^~D&M,e[38]=Q^~z&G,e[39]=ee^~K&W,e[48]=le^~te&ne,e[49]=ue^~re&oe,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=P;else{for(B=0;B<L.length;++B)i[L[B]]=P[L[B]];l&&(void 0===(n=function(){return P}.call(t,r,t,e))||(e.exports=n))}}()},6864:function(e,t,r){"use strict";const n=r(6368),{hasOwnProperty:o}=Object.prototype,{propertyIsEnumerable:s}=Object,i=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)o.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)s.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?i(e,r,p(e[r],t[r],n)):i(e,r,u(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r<t.length;r++)o.call(t,r)&&(a.push(String(r)),i(n,s++,t===e?t[r]:u(t[r])));n=h(n,t,l(t).filter((e=>!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,l(t),r):u(t)}e.exports=function(...e){const t=p(u(c),this!==a&&this||{},c);let r={_:{}};for(const o of e)if(void 0!==o){if(!n(o))throw new TypeError("`"+o+"` is not an Option Object");r=p(r,{_:o},t)}return r._}},6585:e=>{var t=1e3,r=60*t,n=60*r,o=24*n,s=7*o;function i(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var i=/^(-?(?:\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(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*s;case"days":case"day":case"d":return a*o;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(c=e,(l=Math.abs(c))>=o?i(c,l,o,"day"):l>=n?i(c,l,n,"hour"):l>=r?i(c,l,r,"minute"):l>=t?i(c,l,t,"second"):c+" ms"):function(e){var s=Math.abs(e);return s>=o?Math.round(e/o)+"d":s>=n?Math.round(e/n)+"h":s>=r?Math.round(e/r)+"m":s>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8437:(e,t,r)=>{e.exports=r(4327)},4327:function(e,t){!function(r,n){"use strict";var o={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function s(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)return!1;return!0}function i(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<<t|e>>>32-t}function c(e){return e=i(e^=e>>>16,2246822507),(e=i(e^=e>>>13,3266489909))^e>>>16}function l(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t|e[0]>>>32-t]:(t-=32,[e[1]<<t|e[0]>>>32-t,e[0]<<t|e[1]>>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t]:[e[1]<<t-32,0]}function p(e,t){return[e[0]^t[0],e[1]^t[1]]}function f(e){return e=p(e,[0,e[0]>>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}o.x86.hash32=function(e,t){if(o.inputValidation&&!s(e))return n;t=t||0;for(var r=e.length%4,l=e.length-r,u=t,h=0,d=3432918353,p=461845907,f=0;f<l;f+=4)h=i(h=e[f]|e[f+1]<<8|e[f+2]<<16|e[f+3]<<24,d),h=i(h=a(h,15),p),u=i(u=a(u^=h,13),5)+3864292196;switch(h=0,r){case 3:h^=e[f+2]<<16;case 2:h^=e[f+1]<<8;case 1:h=i(h^=e[f],d),u^=h=i(h=a(h,15),p)}return(u=c(u^=e.length))>>>0},o.x86.hash128=function(e,t){if(o.inputValidation&&!s(e))return n;t=t||0;for(var r=e.length%16,l=e.length-r,u=t,h=t,d=t,p=t,f=0,g=0,m=0,y=0,b=597399067,w=2869860233,v=951274213,E=2716044179,S=0;S<l;S+=16)f=e[S]|e[S+1]<<8|e[S+2]<<16|e[S+3]<<24,g=e[S+4]|e[S+5]<<8|e[S+6]<<16|e[S+7]<<24,m=e[S+8]|e[S+9]<<8|e[S+10]<<16|e[S+11]<<24,y=e[S+12]|e[S+13]<<8|e[S+14]<<16|e[S+15]<<24,f=a(f=i(f,b),15),u=a(u^=f=i(f,w),19),u=i(u+=h,5)+1444728091,g=a(g=i(g,w),16),h=a(h^=g=i(g,v),17),h=i(h+=d,5)+197830471,m=a(m=i(m,v),17),d=a(d^=m=i(m,E),15),d=i(d+=p,5)+2530024501,y=a(y=i(y,E),18),p=a(p^=y=i(y,b),13),p=i(p+=u,5)+850148119;switch(f=0,g=0,m=0,y=0,r){case 15:y^=e[S+14]<<16;case 14:y^=e[S+13]<<8;case 13:y=i(y^=e[S+12],E),p^=y=i(y=a(y,18),b);case 12:m^=e[S+11]<<24;case 11:m^=e[S+10]<<16;case 10:m^=e[S+9]<<8;case 9:m=i(m^=e[S+8],v),d^=m=i(m=a(m,17),E);case 8:g^=e[S+7]<<24;case 7:g^=e[S+6]<<16;case 6:g^=e[S+5]<<8;case 5:g=i(g^=e[S+4],w),h^=g=i(g=a(g,16),v);case 4:f^=e[S+3]<<24;case 3:f^=e[S+2]<<16;case 2:f^=e[S+1]<<8;case 1:f=i(f^=e[S],b),u^=f=i(f=a(f,15),w)}return u^=e.length,u+=h^=e.length,u+=d^=e.length,h+=u+=p^=e.length,d+=u,p+=u,u=c(u),u+=h=c(h),u+=d=c(d),h+=u+=p=c(p),d+=u,p+=u,("00000000"+(u>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(p>>>0).toString(16)).slice(-8)},o.x64.hash128=function(e,t){if(o.inputValidation&&!s(e))return n;t=t||0;for(var r=e.length%16,i=e.length-r,a=[0,t],c=[0,t],g=[0,0],m=[0,0],y=[2277735313,289559509],b=[1291169091,658871167],w=0;w<i;w+=16)g=[e[w+4]|e[w+5]<<8|e[w+6]<<16|e[w+7]<<24,e[w]|e[w+1]<<8|e[w+2]<<16|e[w+3]<<24],m=[e[w+12]|e[w+13]<<8|e[w+14]<<16|e[w+15]<<24,e[w+8]|e[w+9]<<8|e[w+10]<<16|e[w+11]<<24],g=h(g=u(g,y),31),a=l(a=h(a=p(a,g=u(g,b)),27),c),a=l(u(a,[0,5]),[0,1390208809]),m=h(m=u(m,b),33),c=l(c=h(c=p(c,m=u(m,y)),31),a),c=l(u(c,[0,5]),[0,944331445]);switch(g=[0,0],m=[0,0],r){case 15:m=p(m,d([0,e[w+14]],48));case 14:m=p(m,d([0,e[w+13]],40));case 13:m=p(m,d([0,e[w+12]],32));case 12:m=p(m,d([0,e[w+11]],24));case 11:m=p(m,d([0,e[w+10]],16));case 10:m=p(m,d([0,e[w+9]],8));case 9:m=u(m=p(m,[0,e[w+8]]),b),c=p(c,m=u(m=h(m,33),y));case 8:g=p(g,d([0,e[w+7]],56));case 7:g=p(g,d([0,e[w+6]],48));case 6:g=p(g,d([0,e[w+5]],40));case 5:g=p(g,d([0,e[w+4]],32));case 4:g=p(g,d([0,e[w+3]],24));case 3:g=p(g,d([0,e[w+2]],16));case 2:g=p(g,d([0,e[w+1]],8));case 1:g=u(g=p(g,[0,e[w]]),y),a=p(a,g=u(g=h(g,31),b))}return a=l(a=p(a,[0,e.length]),c=p(c,[0,e.length])),c=l(c,a),a=l(a=f(a),c=f(c)),c=l(c,a),("00000000"+(a[0]>>>0).toString(16)).slice(-8)+("00000000"+(a[1]>>>0).toString(16)).slice(-8)+("00000000"+(c[0]>>>0).toString(16)).slice(-8)+("00000000"+(c[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=o),t.murmurHash3=o}()},5507:function(e,t){(function(){var e,r,n,o,s,i,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,o,s,i,a;for(t=[],o=s=0;s<=3&&0!==e.length;o=++s){if(o>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}i=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(i)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new 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 new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},o=(n=function(e){return e.charCodeAt(0)})("0"),i=n("a"),s=n("A"),r=function(e){var t,r,a,c,l;for(c=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")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=r)c=c*t+(n(e[a])-o)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-s)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,o;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(o=e.split("/",2),e=o[0],t=o[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new 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)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(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(c(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(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},2549:(e,t,r)=>{"use strict";e.exports=r(9100)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},744:(e,t,r)=>{"use strict";var n=t,o=r(5643),s=r(3262);function i(e,t,r,n){var s=!1;if(t.resolvedType)if(t.resolvedType instanceof o){e("switch(d%s){",n);for(var i=t.resolvedType.values,a=Object.keys(i),c=0;c<a.length;++c)i[a[c]]!==t.typeDefault||s||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),s=!0),e("case%j:",a[c])("case %i:",i[a[c]])("m%s=%j",n,i[a[c]])("break");e("}")}else e('if(typeof d%s!=="object")',n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",n,r,n);else{var l=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,l)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,l?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof o?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var s=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,s?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=s.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n<t.length;++n){var a=t[n].resolve(),c=s.safeProp(a.name);a.map?(r("if(d%s){",c)('if(typeof d%s!=="object")',c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),i(r,a,n,c+"[ks[i]]")("}")("}")):a.repeated?(r("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),i(r,a,n,c+"[i]")("}")("}")):(a.resolvedType instanceof o||r("if(d%s!=null){",c),i(r,a,n,c),a.resolvedType instanceof o||r("}"))}return r("return m")},n.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var r=s.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),n=[],i=[],c=[],l=0;l<t.length;++l)t[l].partOf||(t[l].resolve().repeated?n:t[l].map?i:c).push(t[l]);if(n.length){for(r("if(o.arrays||o.defaults){"),l=0;l<n.length;++l)r("d%s=[]",s.safeProp(n[l].name));r("}")}if(i.length){for(r("if(o.objects||o.defaults){"),l=0;l<i.length;++l)r("d%s={}",s.safeProp(i[l].name));r("}")}if(c.length){for(r("if(o.defaults){"),l=0;l<c.length;++l){var u=c[l],h=s.safeProp(u.name);if(u.resolvedType instanceof o)r("d%s=o.enums===String?%j:%j",h,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)r("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",h)("}else")("d%s=o.longs===String?%j:%i",h,u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var d="["+Array.prototype.slice.call(u.typeDefault).join(",")+"]";r("if(o.bytes===String)d%s=%j",h,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%s",h,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",h,h)("}")}else r("d%s=%j",h,u.typeDefault)}r("}")}var p=!1;for(l=0;l<t.length;++l){u=t[l];var f=e._fieldsArray.indexOf(u);h=s.safeProp(u.name),u.map?(p||(p=!0,r("var ks2")),r("if(m%s&&(ks2=Object.keys(m%s)).length){",h,h)("d%s={}",h)("for(var j=0;j<ks2.length;++j){"),a(r,u,f,h+"[ks2[j]]")("}")):u.repeated?(r("if(m%s&&m%s.length){",h,h)("d%s=[]",h)("for(var j=0;j<m%s.length;++j){",h),a(r,u,f,h+"[j]")("}")):(r("if(m%s!=null&&m.hasOwnProperty(%j)){",h,u.name),a(r,u,f,h),u.partOf&&r("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),r("}")}return r("return d")}},7728:(e,t,r)=>{"use strict";e.exports=function(e){var t=s.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()");e.group&&t("if((t&7)===4)")("break"),t("switch(t>>>3){");for(var r=0;r<e.fieldsArray.length;++r){var a=e._fieldsArray[r].resolve(),c=a.resolvedType instanceof n?"int32":a.type,l="m"+s.safeProp(a.name);t("case %i: {",a.id),a.map?(t("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),void 0!==o.defaults[a.keyType]?t("k=%j",o.defaults[a.keyType]):t("k=null"),void 0!==o.defaults[c]?t("value=%j",o.defaults[c]):t("value=null"),t("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===o.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==o.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==o.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,c)("}else"),void 0===o.basic[c]?t(a.resolvedType.group?"%s.push(types[%i].decode(r))":"%s.push(types[%i].decode(r,r.uint32()))",l,r):t("%s.push(r.%s())",l,c)):void 0===o.basic[c]?t(a.resolvedType.group?"%s=types[%i].decode(r)":"%s=types[%i].decode(r,r.uint32())",l,r):t("%s=r.%s()",l,c),t("break")("}")}for(t("default:")("r.skipType(t&7)")("break")("}")("}"),r=0;r<e._fieldsArray.length;++r){var u=e._fieldsArray[r];u.required&&t("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",i(u))}return t("return m")};var n=r(5643),o=r(361),s=r(3262);function i(e){return"missing required '"+e.name+"'"}},1080:(e,t,r)=>{"use strict";e.exports=function(e){for(var t,r=s.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(s.compareFieldsById),c=0;c<a.length;++c){var l=a[c].resolve(),u=e._fieldsArray.indexOf(l),h=l.resolvedType instanceof n?"int32":l.type,d=o.basic[h];t="m"+s.safeProp(l.name),l.map?(r("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",t,l.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",t)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(l.id<<3|2)>>>0,8|o.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==o.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?i(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?i(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),o=r(361),s=r(3262);function i(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},5643:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Enum";var o=r(8923),s=r(3262);function i(e,t,r,o,s,i){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=o,this.comments=s||{},this.valuesOptions=i,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c<a.length;++c)"number"==typeof t[a[c]]&&(this.valuesById[this.values[a[c]]=t[a[c]]]=a[c])}i.fromJSON=function(e,t){var r=new i(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,r},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},i.prototype.add=function(e,t,r,n){if(!s.isString(e))throw TypeError("name must be a string");if(!s.isInteger(t))throw TypeError("id must be an integer");if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=r||null,this},i.prototype.remove=function(e){if(!s.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},i.prototype.isReservedId=function(e){return o.isReservedId(this.reserved,e)},i.prototype.isReservedName=function(e){return o.isReservedName(this.reserved,e)}},1344:(e,t,r)=>{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var o,s=r(5643),i=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,o,s,l,u){if(a.isObject(o)?(u=s,l=o,o=s=void 0):a.isObject(s)&&(u=l,l=s,s=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==o&&!c.test(o=o.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==s&&!a.isString(s))throw TypeError("extend must be a string");"proto3_optional"===o&&(o="optional"),this.rule=o&&"optional"!==o?o:void 0,this.type=r,this.id=t,this.extend=s||void 0,this.required="required"===o,this.optional=!this.required,this.repeated="repeated"===o,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==i.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=i.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof o?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof s)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof o&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"==typeof t?t=a.decorateType(t).name:t&&"object"==typeof t&&(t=a.decorateEnum(t).name),function(o,s){a.decorateType(o.constructor).add(new l(s,e,t,r,{default:n}))}},l._configure=function(e){o=e}},5325:(e,t,r)=>{"use strict";var n=e.exports=r(4394);n.build="light",n.load=function(e,t,r){return"function"==typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(1080),n.decoder=r(7728),n.verifier=r(420),n.converter=r(744),n.ReflectionObject=r(7209),n.Namespace=r(8923),n.Root=r(5330),n.Enum=r(5643),n.Type=r(7882),n.Field=r(1344),n.OneOf=r(1457),n.MapField=r(8252),n.Service=r(9687),n.Method=r(8811),n.Message=r(2551),n.wrappers=r(6434),n.types=r(361),n.util=r(3262),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4394:(e,t,r)=>{"use strict";var n=t;function o(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(3449),n.BufferWriter=r(818),n.Reader=r(6237),n.BufferReader=r(3158),n.util=r(3610),n.rpc=r(5047),n.roots=r(4529),n.configure=o,o()},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},8252:(e,t,r)=>{"use strict";e.exports=i;var n=r(1344);((i.prototype=Object.create(n.prototype)).constructor=i).className="MapField";var o=r(361),s=r(3262);function i(e,t,r,o,i,a){if(n.call(this,e,t,o,void 0,void 0,i,a),!s.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}i.fromJSON=function(e,t){return new i(e,t.id,t.keyType,t.type,t.options,t.comment)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},i.prototype.resolve=function(){if(this.resolved)return this;if(void 0===o.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},i.d=function(e,t,r){return"function"==typeof r?r=s.decorateType(r).name:r&&"object"==typeof r&&(r=s.decorateEnum(r).name),function(n,o){s.decorateType(n.constructor).add(new i(o,e,t,r))}}},2551:(e,t,r)=>{"use strict";e.exports=o;var n=r(3610);function o(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}o.create=function(e){return this.$type.create(e)},o.encode=function(e,t){return this.$type.encode(e,t)},o.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},o.decode=function(e){return this.$type.decode(e)},o.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},o.verify=function(e){return this.$type.verify(e)},o.fromObject=function(e){return this.$type.fromObject(e)},o.toObject=function(e,t){return this.$type.toObject(e,t)},o.prototype.toJSON=function(){return this.$type.toObject(this,n.toJSONOptions)}},8811:(e,t,r)=>{"use strict";e.exports=s;var n=r(7209);((s.prototype=Object.create(n.prototype)).constructor=s).className="Method";var o=r(3262);function s(e,t,r,s,i,a,c,l,u){if(o.isObject(i)?(c=i,i=a=void 0):o.isObject(a)&&(c=a,a=void 0),void 0!==t&&!o.isString(t))throw TypeError("type must be a string");if(!o.isString(r))throw TypeError("requestType must be a string");if(!o.isString(s))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!i||void 0,this.responseType=s,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}s.fromJSON=function(e,t){return new s(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},8923:(e,t,r)=>{"use strict";e.exports=h;var n=r(7209);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var o,s,i,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;n<e.length;++n)r[e[n].name]=e[n].toJSON(t);return r}}function h(e,t){n.call(this,e,t),this.nested=void 0,this._nestedArray=null}function d(e){return e._nestedArray=null,e}h.fromJSON=function(e,t){return new h(e,t.options).addJSON(t.nested)},h.arrayToJSON=u,h.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(h.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=c.toArray(this.nested))}}),h.prototype.toJSON=function(e){return c.toObject(["options",this.options,"nested",u(this.nestedArray,e)])},h.prototype.addJSON=function(e){if(e)for(var t,r=Object.keys(e),n=0;n<r.length;++n)t=e[r[n]],this.add((void 0!==t.fields?o.fromJSON:void 0!==t.values?i.fromJSON:void 0!==t.methods?s.fromJSON:void 0!==t.id?a.fromJSON:h.fromJSON)(r[n],t));return this},h.prototype.get=function(e){return this.nested&&this.nested[e]||null},h.prototype.getEnum=function(e){if(this.nested&&this.nested[e]instanceof i)return this.nested[e].values;throw Error("no such enum: "+e)},h.prototype.add=function(e){if(!(e instanceof a&&void 0!==e.extend||e instanceof o||e instanceof l||e instanceof i||e instanceof s||e instanceof h))throw TypeError("object must be a valid nested object");if(this.nested){var t=this.get(e.name);if(t){if(!(t instanceof h&&e instanceof h)||t instanceof o||t instanceof s)throw Error("duplicate name '"+e.name+"' in "+this);for(var r=t.nestedArray,n=0;n<r.length;++n)e.add(r[n]);this.remove(t),this.nested||(this.nested={}),e.setOptions(t.options,!0)}}else this.nested={};return this.nested[e.name]=e,e.onAdd(this),d(this)},h.prototype.remove=function(e){if(!(e instanceof n))throw TypeError("object must be a ReflectionObject");if(e.parent!==this)throw Error(e+" is not a member of "+this);return delete this.nested[e.name],Object.keys(this.nested).length||(this.nested=void 0),e.onRemove(this),d(this)},h.prototype.define=function(e,t){if(c.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;e.length>0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t<e.length;)e[t]instanceof h?e[t++].resolveAll():e[t++].resolve();return this.resolve()},h.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),c.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.get(e[0]);if(n){if(1===e.length){if(!t||t.indexOf(n.constructor)>-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var o=0;o<this.nestedArray.length;++o)if(this._nestedArray[o]instanceof h&&(n=this._nestedArray[o].lookup(e,t,!0)))return n;return null===this.parent||r?null:this.parent.lookup(e,t)},h.prototype.lookupType=function(e){var t=this.lookup(e,[o]);if(!t)throw Error("no such type: "+e);return t},h.prototype.lookupEnum=function(e){var t=this.lookup(e,[i]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},h.prototype.lookupTypeOrEnum=function(e){var t=this.lookup(e,[o,i]);if(!t)throw Error("no such Type or Enum '"+e+"' in "+this);return t},h.prototype.lookupService=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},h._configure=function(e,t,r){o=e,s=t,i=r}},7209:(e,t,r)=>{"use strict";e.exports=s,s.className="ReflectionObject";var n,o=r(3262);function s(e,t){if(!o.isString(e))throw TypeError("name must be a string");if(t&&!o.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(s.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),s.prototype.toJSON=function(){throw Error()},s.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},s.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},s.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},s.prototype.getOption=function(e){if(this.options)return this.options[e]},s.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},s.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var s=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(s){var i=s[e];o.setProperty(i,r,t)}else(s={})[e]=o.setProperty({},r,t),n.push(s)}else{var a={};a[e]=t,n.push(a)}return this},s.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)this.setOption(r[n],e[r[n]],t);return this},s.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},s._configure=function(e){n=e}},1457:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="OneOf";var o=r(1344),s=r(3262);function i(e,t,r,o){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=o}function a(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}i.fromJSON=function(e,t){return new i(e,t.oneof,t.options,t.comment)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},i.prototype.add=function(e){if(!(e instanceof o))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,a(this),this},i.prototype.remove=function(e){if(!(e instanceof o))throw TypeError("field must be a Field");var t=this.fieldsArray.indexOf(e);if(t<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(t,1),(t=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(t,1),e.partOf=null,this},i.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t<this.oneof.length;++t){var r=e.get(this.oneof[t]);r&&!r.partOf&&(r.partOf=this,this.fieldsArray.push(r))}a(this)},i.prototype.onRemove=function(e){for(var t,r=0;r<this.fieldsArray.length;++r)(t=this.fieldsArray[r]).parent&&t.parent.remove(t);n.prototype.onRemove.call(this,e)},i.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,r){s.decorateType(t.constructor).add(new i(r,e)),Object.defineProperty(t,r,{get:s.oneOfGetter(e),set:s.oneOfSetter(e)})}}},4863:(e,t,r)=>{"use strict";e.exports=k,k.filename=null,k.defaults={keepCase:!1};var n=r(527),o=r(5330),s=r(7882),i=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(361),p=r(3262),f=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,m=/^0[x][0-9a-fA-F]+$/,y=/^-?0[x][0-9a-fA-F]+$/,b=/^0[0-7]+$/,w=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,A=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function k(e,t,r){t instanceof o||(r=t,t=new o),r||(r=k.defaults);var C,I,x,T,_,N=r.preferTrailingComment||!1,P=n(e,r.alternateCommentMode||!1),L=P.next,B=P.push,O=P.peek,R=P.skip,D=P.cmnt,U=!0,M=!1,F=t,$=r.keepCase?function(e){return e}:p.camelCase;function q(e,t,r){var n=k.filename;return r||(k.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+P.line+")")}function H(){var e,t=[];do{if('"'!==(e=L())&&"'"!==e)throw q(e);t.push(L()),R(e),e=O()}while('"'===e||"'"===e);return t.join("")}function j(e){var t=L();switch(t){case"'":case'"':return B(t),H();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e){var t=1;switch("-"===e.charAt(0)&&(t=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return t*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return t*parseInt(e,10);if(m.test(e))return t*parseInt(e,16);if(b.test(e))return t*parseInt(e,8);if(v.test(e))return t*parseFloat(e);throw q(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw q(t,"value")}}function V(e,t){var r,n;do{!t||'"'!==(r=O())&&"'"!==r?e.push([n=z(L()),R("to",!0)?z(L()):n]):e.push(H())}while(R(",",!0));var o={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(o,(function(e){if("option"!==e)throw q(e);ee(o,e),R(";")}),(function(){ne(o)}))}function z(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw q(e,"id");if(g.test(e))return parseInt(e,10);if(y.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw q(e,"id")}function K(){if(void 0!==C)throw q("package");if(C=L(),!S.test(C))throw q(C,"name");F=F.define(C),R(";")}function G(){var e,t=O();switch(t){case"weak":e=x||(x=[]),L();break;case"public":L();default:e=I||(I=[])}t=H(),R(";"),e.push(t)}function W(){if(R("="),T=H(),!(M="proto3"===T)&&"proto2"!==T)throw q(T,"syntax");t.setOption("syntax",T),R(";")}function J(e,t){switch(t){case"option":return ee(e,t),R(";"),!0;case"message":return Y(e,t),!0;case"enum":return Q(e,t),!0;case"service":return function(e,t){if(!E.test(t=L()))throw q(t,"service name");var r=new u(t);X(r,(function(e){if(!J(r,e)){if("rpc"!==e)throw q(e);!function(e,t){var r=D(),n=t;if(!E.test(t=L()))throw q(t,"name");var o,s,i,a,c=t;if(R("("),R("stream",!0)&&(s=!0),!S.test(t=L()))throw q(t);if(o=t,R(")"),R("returns"),R("("),R("stream",!0)&&(a=!0),!S.test(t=L()))throw q(t);i=t,R(")");var l=new h(c,n,o,i,s,a);l.comment=r,X(l,(function(e){if("option"!==e)throw q(e);ee(l,e),R(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=L()))throw q(t,"reference");var r=t;X(null,(function(t){switch(t){case"required":case"repeated":Z(e,t,r);break;case"optional":Z(e,M?"proto3_optional":"optional",r);break;default:if(!M||!S.test(t))throw q(t);B(t),Z(e,"optional",r)}}))}(e,t),!0}return!1}function X(e,t,r){var n=P.line;if(e&&("string"!=typeof e.comment&&(e.comment=D()),e.filename=k.filename),R("{",!0)){for(var o;"}"!==(o=L());)t(o);R(";",!0)}else r&&r(),R(";"),e&&("string"!=typeof e.comment||N)&&(e.comment=D(n)||e.comment)}function Y(e,t){if(!E.test(t=L()))throw q(t,"type name");var r=new s(t);X(r,(function(e){if(!J(r,e))switch(e){case"map":!function(e){R("<");var t=L();if(void 0===d.mapKey[t])throw q(t,"type");R(",");var r=L();if(!S.test(r))throw q(r,"type");R(">");var n=L();if(!E.test(n))throw q(n,"name");R("=");var o=new a($(n),z(L()),t,r);X(o,(function(e){if("option"!==e)throw q(e);ee(o,e),R(";")}),(function(){ne(o)})),e.add(o)}(r);break;case"required":case"repeated":Z(r,e);break;case"optional":Z(r,M?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=L()))throw q(t,"name");var r=new c($(t));X(r,(function(e){"option"===e?(ee(r,e),R(";")):(B(e),Z(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":V(r.extensions||(r.extensions=[]));break;case"reserved":V(r.reserved||(r.reserved=[]),!0);break;default:if(!M||!S.test(e))throw q(e);B(e),Z(r,"optional")}})),e.add(r)}function Z(e,t,r){var n=L();if("group"!==n){for(;n.endsWith(".")||O().startsWith(".");)n+=L();if(!S.test(n))throw q(n,"type");var o=L();if(!E.test(o))throw q(o,"name");o=$(o),R("=");var a=new i(o,z(L()),n,t,r);if(X(a,(function(e){if("option"!==e)throw q(e);ee(a,e),R(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+o);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);M||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=L();if(!E.test(r))throw q(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),R("=");var o=z(L()),a=new s(r);a.group=!0;var c=new i(n,o,r,t);c.filename=k.filename,X(a,(function(e){switch(e){case"option":ee(a,e),R(";");break;case"required":case"repeated":Z(a,e);break;case"optional":Z(a,M?"proto3_optional":"optional");break;case"message":Y(a,e);break;case"enum":Q(a,e);break;default:throw q(e)}})),e.add(a).add(c)}(e,t)}function Q(e,t){if(!E.test(t=L()))throw q(t,"name");var r=new l(t);X(r,(function(e){switch(e){case"option":ee(r,e),R(";");break;case"reserved":V(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw q(t,"name");R("=");var r=z(L(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(n,(function(e){if("option"!==e)throw q(e);ee(n,e),R(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=R("(",!0);if(!S.test(t=L()))throw q(t,"name");var n,o=t,s=o;r&&(R(")"),s=o="("+o+")",t=O(),A.test(t)&&(n=t.slice(1),o+=t,L())),R("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,s,te(e,o),n)}function te(e,t){if(R("{",!0)){for(var r={};!R("}",!0);){if(!E.test(_=L()))throw q(_,"name");if(null===_)throw q(_,"end of input");var n,o=_;if(R(":",!0),"{"===O())n=te(e,t+"."+_);else if("["===O()){var s;if(n=[],R("[",!0)){do{s=j(!0),n.push(s)}while(R(",",!0));R("]"),void 0!==s&&re(e,t+"."+_,s)}}else n=j(!0),re(e,t+"."+_,n);var i=r[o];i&&(n=[].concat(i).concat(n)),r[o]=n,R(",",!0),R(";",!0)}return r}var a=j(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(R("[",!0)){do{ee(e,"option")}while(R(",",!0));R("]")}return e}for(;null!==(_=L());)switch(_){case"package":if(!U)throw q(_);K();break;case"import":if(!U)throw q(_);G();break;case"syntax":if(!U)throw q(_);W();break;case"option":ee(F,_),R(";");break;default:if(J(F,_)){U=!1;continue}throw q(_)}return k.filename=null,{package:C,imports:I,weakImports:x,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,o=r(3610),s=o.LongBits,i=o.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},h=function(){return o.Buffer?function(e){return(c.create=function(e){return o.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new s(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(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}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;if(t=0,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 a(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")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new s(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=o.Array.prototype.subarray||o.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=o.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=o.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=o.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return i.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(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},c._configure=function(e){n=e,c.create=h(),n._configure();var t=o.Long?"toLong":"toNumber";o.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3158:(e,t,r)=>{"use strict";e.exports=s;var n=r(6237);(s.prototype=Object.create(n.prototype)).constructor=s;var o=r(3610);function s(e){n.call(this,e)}s._configure=function(){o.Buffer&&(s.prototype._slice=o.Buffer.prototype.slice)},s.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},s._configure()},5330:(e,t,r)=>{"use strict";e.exports=h;var n=r(8923);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var o,s,i,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var o=this;if(!n)return u.asPromise(e,o,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in i)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){s.filename=e;var n,i=s(t,o,r),h=0;if(i.imports)for(;h<i.imports.length;++h)(n=l(i.imports[h])||o.resolvePath(e,i.imports[h]))&&p(n);if(i.weakImports)for(h=0;h<i.weakImports.length;++h)(n=l(i.weakImports[h])||o.resolvePath(e,i.weakImports[h]))&&p(n,!0)}else o.setOptions(t.options).addJSON(t.nested)}catch(e){c(e)}a||f||c(null,o)}function p(e,t){if(e=l(e)||e,!(o.files.indexOf(e)>-1))if(o.files.push(e),e in i)a?h(e,i[e]):(++f,setTimeout((function(){--f,h(e,i[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,o.fetch(e,(function(r,s){--f,n&&(r?t?f||c(null,o):c(r):h(e,s))}))}var f=0;u.isString(t)&&(t=[t]);for(var g,m=0;m<t.length;++m)(g=o.resolvePath("",t[m]))&&p(g);if(a)return o;f||c(null,o)},h.prototype.loadSync=function(e,t){if(!u.isNode)throw Error("not supported");return this.load(e,t,d)},h.prototype.resolveAll=function(){if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map((function(e){return"'extend "+e.extend+"' in "+e.parent.fullName})).join(", "));return n.prototype.resolveAll.call(this)};var p=/^[A-Z]/;function f(e,t){var r=t.parent.lookup(t.extend);if(r){var n=new a(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(n.name)||(n.declaringField=t,t.extensionField=n,r.add(n)),!0}return!1}h.prototype._handleAdd=function(e){if(e instanceof a)void 0===e.extend||e.extensionField||f(0,e)||this.deferred.push(e);else if(e instanceof c)p.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof l)){if(e instanceof o)for(var t=0;t<this.deferred.length;)f(0,this.deferred[t])?this.deferred.splice(t,1):++t;for(var r=0;r<e.nestedArray.length;++r)this._handleAdd(e._nestedArray[r]);p.test(e.name)&&(e.parent[e.name]=e)}},h.prototype._handleRemove=function(e){if(e instanceof a){if(void 0!==e.extend)if(e.extensionField)e.extensionField.parent.remove(e.extensionField),e.extensionField=null;else{var t=this.deferred.indexOf(e);t>-1&&this.deferred.splice(t,1)}}else if(e instanceof c)p.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r<e.nestedArray.length;++r)this._handleRemove(e._nestedArray[r]);p.test(e.name)&&delete e.parent[e.name]}},h._configure=function(e,t,r){o=e,s=t,i=r}},4529:e=>{"use strict";e.exports={}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},7595:(e,t,r)=>{"use strict";e.exports=o;var n=r(3610);function o(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(o.prototype=Object.create(n.EventEmitter.prototype)).constructor=o,o.prototype.rpcCall=function e(t,r,o,s,i){if(!s)throw TypeError("request must be specified");var a=this;if(!i)return n.asPromise(e,a,t,r,o,s);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](s).finish(),(function(e,r){if(e)return a.emit("error",e,t),i(e);if(null!==r){if(!(r instanceof o))try{r=o[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),i(e)}return a.emit("data",r,t),i(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){i(e)}),0)}else setTimeout((function(){i(Error("already ended"))}),0)},o.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},9687:(e,t,r)=>{"use strict";e.exports=a;var n=r(8923);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var o=r(8811),s=r(3262),i=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),s=0;s<n.length;++s)r.add(o.fromJSON(n[s],t.methods[n[s]]));return t.nested&&r.addJSON(t.nested),r.comment=t.comment,r},a.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&Boolean(e.keepComments);return s.toObject(["options",t&&t.options||void 0,"methods",n.arrayToJSON(this.methodsArray,e)||{},"nested",t&&t.nested||void 0,"comment",r?this.comment:void 0])},Object.defineProperty(a.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=s.toArray(this.methods))}}),a.prototype.get=function(e){return this.methods[e]||n.prototype.get.call(this,e)},a.prototype.resolveAll=function(){for(var e=this.methodsArray,t=0;t<e.length;++t)e[t].resolve();return n.prototype.resolve.call(this)},a.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);return e instanceof o?(this.methods[e.name]=e,e.parent=this,c(this)):n.prototype.add.call(this,e)},a.prototype.remove=function(e){if(e instanceof o){if(this.methods[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.methods[e.name],e.parent=null,c(this)}return n.prototype.remove.call(this,e)},a.prototype.create=function(e,t,r){for(var n,o=new i.Service(e,t,r),a=0;a<this.methodsArray.length;++a){var c=s.lcFirst((n=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");o[c]=s.codegen(["r","c"],s.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:n,q:n.resolvedRequestType.ctor,s:n.resolvedResponseType.ctor})}return o}},527:e=>{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,o=/^ *[*/]+ */,s=/^\s*\*?\/*/,i=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],m=null;function y(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(i),g=0;g<h.length;++g)h[g]=h[g].replace(c?s:o,"").trim();l.text=h.join("\n").trim(),f[d]=l,p=d}function v(t){var r=E(t),n=e.substring(t,r);return/^\s*\/\//.test(n)}function E(e){for(var t=e;t<h&&"\n"!==b(t);)t++;return t}function S(){if(g.length>0)return g.shift();if(m)return function(){var t="'"===m?n:r;t.lastIndex=l-1;var o=t.exec(e);if(!o)throw y("string");return l=t.lastIndex,A(m),m=null,u(o[1])}();var o,s,i,p,f,S=0===l;do{if(l===h)return null;for(o=!1;a.test(i=b(l));)if("\n"===i&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw y("comment");if("/"===b(l))if(c){if(p=l,f=!1,v(l-1)){f=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(v(l))}else l=Math.min(h,E(l)+1);f&&(w(p,l,S),S=!0),d++,o=!0}else{for(f="/"===b(p=l+1);"\n"!==b(++l);)if(l===h)return null;++l,f&&(w(p,l-1,S),S=!0),++d,o=!0}else{if("*"!==(i=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===i&&++d,++l===h)throw y("comment");s=i,i=b(l)}while("*"!==s||"/"!==i);++l,f&&(w(p,l-2,S),S=!0),o=!0}}}while(o);var k=l;if(t.lastIndex=0,!t.test(b(k++)))for(;k<h&&!t.test(b(k));)++k;var C=e.substring(l,l=k);return'"'!==C&&"'"!==C||(m=C),C}function A(e){g.push(e)}function k(){if(!g.length){var e=S();if(null===e)return null;A(e)}return g[0]}return Object.defineProperty({next:S,peek:k,push:A,skip:function(e,t){var r=k();if(r===e)return S(),!0;if(!t)throw y("token '"+r+"', '"+e+"' expected");return!1},cmnt:function(e){var t,r=null;return void 0===e?(t=f[d-1],delete f[d-1],t&&(c||"*"===t.type||t.lineEmpty)&&(r=t.leading?t.text:null)):(p<e&&k(),t=f[e],delete f[e],!t||t.lineEmpty||!c&&"/"!==t.type||(r=t.leading?null:t.text)),r}},"line",{get:function(){return d}})}h.unescape=u},7882:(e,t,r)=>{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var o=r(5643),s=r(1457),i=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),m=r(744),y=r(6434);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],n=r.id;if(this._fieldsById[n])throw Error("duplicate id "+n+" in "+this);this._fieldsById[n]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=b.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof l||((e.prototype=new l).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,l,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var n={};for(r=0;r<this.oneofsArray.length;++r)n[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,n)}}}),b.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),n=0;n<e.fieldsArray.length;++n)(t=e._fieldsArray[n]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},b.fromJSON=function(e,t){var r=new b(e,t.options);r.extensions=t.extensions,r.reserved=t.reserved;for(var l=Object.keys(t.fields),u=0;u<l.length;++u)r.add((void 0!==t.fields[l[u]].keyType?a.fromJSON:i.fromJSON)(l[u],t.fields[l[u]]));if(t.oneofs)for(l=Object.keys(t.oneofs),u=0;u<l.length;++u)r.add(s.fromJSON(l[u],t.oneofs[l[u]]));if(t.nested)for(l=Object.keys(t.nested),u=0;u<l.length;++u){var h=t.nested[l[u]];r.add((void 0!==h.id?i.fromJSON:void 0!==h.fields?b.fromJSON:void 0!==h.values?o.fromJSON:void 0!==h.methods?c.fromJSON:n.fromJSON)(l[u],h))}return t.extensions&&t.extensions.length&&(r.extensions=t.extensions),t.reserved&&t.reserved.length&&(r.reserved=t.reserved),t.group&&(r.group=!0),t.comment&&(r.comment=t.comment),r},b.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&Boolean(e.keepComments);return d.toObject(["options",t&&t.options||void 0,"oneofs",n.arrayToJSON(this.oneofsArray,e),"fields",n.arrayToJSON(this.fieldsArray.filter((function(e){return!e.declaringField})),e)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",t&&t.nested||void 0,"comment",r?this.comment:void 0])},b.prototype.resolveAll=function(){for(var e=this.fieldsArray,t=0;t<e.length;)e[t++].resolve();var r=this.oneofsArray;for(t=0;t<r.length;)r[t++].resolve();return n.prototype.resolveAll.call(this)},b.prototype.get=function(e){return this.fields[e]||this.oneofs&&this.oneofs[e]||this.nested&&this.nested[e]||null},b.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);if(e instanceof i&&void 0===e.extend){if(this._fieldsById?this._fieldsById[e.id]:this.fieldsById[e.id])throw Error("duplicate id "+e.id+" in "+this);if(this.isReservedId(e.id))throw Error("id "+e.id+" is reserved in "+this);if(this.isReservedName(e.name))throw Error("name '"+e.name+"' is reserved in "+this);return e.parent&&e.parent.remove(e),this.fields[e.name]=e,e.message=this,e.onAdd(this),w(this)}return e instanceof s?(this.oneofs||(this.oneofs={}),this.oneofs[e.name]=e,e.onAdd(this),w(this)):n.prototype.add.call(this,e)},b.prototype.remove=function(e){if(e instanceof i&&void 0===e.extend){if(!this.fields||this.fields[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.fields[e.name],e.parent=null,e.onRemove(this),w(this)}if(e instanceof s){if(!this.oneofs||this.oneofs[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.oneofs[e.name],e.parent=null,e.onRemove(this),w(this)}return n.prototype.remove.call(this,e)},b.prototype.isReservedId=function(e){return n.isReservedId(this.reserved,e)},b.prototype.isReservedName=function(e){return n.isReservedName(this.reserved,e)},b.prototype.create=function(e){return new this.ctor(e)},b.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=p(this)({Writer:h,types:t,util:d}),this.decode=f(this)({Reader:u,types:t,util:d}),this.verify=g(this)({types:t,util:d}),this.fromObject=m.fromObject(this)({types:t,util:d}),this.toObject=m.toObject(this)({types:t,util:d});var n=y[e];if(n){var o=Object.create(this);o.fromObject=this.fromObject,this.fromObject=n.fromObject.bind(o),o.toObject=this.toObject,this.toObject=n.toObject.bind(o)}return this},b.prototype.encode=function(e,t){return this.setup().encode(e,t)},b.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},b.prototype.decode=function(e,t){return this.setup().decode(e,t)},b.prototype.decodeDelimited=function(e){return e instanceof u||(e=u.create(e)),this.decode(e,e.uint32())},b.prototype.verify=function(e){return this.setup().verify(e)},b.prototype.fromObject=function(e){return this.setup().fromObject(e)},b.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},b.d=function(e){return function(t){d.decorateType(t,e)}}},361:(e,t,r)=>{"use strict";var n=t,o=r(3262),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(e,t){var r=0,n={};for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}n.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",o.emptyArray,null]),n.long=i([0,0,0,1,1],7),n.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},3262:(e,t,r)=>{"use strict";var n,o,s=e.exports=r(3610),i=r(4529);s.codegen=r(8561),s.fetch=r(5212),s.path=r(9207),s.fs=s.inquire("fs"),s.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n<t.length;)r[n]=e[t[n++]];return r}return[]},s.toObject=function(e){for(var t={},r=0;r<e.length;){var n=e[r++],o=e[r++];void 0!==o&&(t[n]=o)}return t};var a=/\\/g,c=/"/g;s.isReserved=function(e){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(e)},s.safeProp=function(e){return!/^[$\w_]+$/.test(e)||s.isReserved(e)?'["'+e.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+e},s.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var l=/_([a-z])/g;s.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(l,(function(e,t){return t.toUpperCase()}))},s.compareFieldsById=function(e,t){return e.id-t.id},s.decorateType=function(e,t){if(e.$type)return t&&e.$type.name!==t&&(s.decorateRoot.remove(e.$type),e.$type.name=t,s.decorateRoot.add(e.$type)),e.$type;n||(n=r(7882));var o=new n(t||e.name);return s.decorateRoot.add(o),o.ctor=e,Object.defineProperty(e,"$type",{value:o,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:o,enumerable:!1}),o};var u=0;s.decorateEnum=function(e){if(e.$type)return e.$type;o||(o=r(5643));var t=new o("Enum"+u++,e);return s.decorateRoot.add(t),Object.defineProperty(e,"$type",{value:t,enumerable:!1}),t},s.setProperty=function(e,t,r){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");return function e(t,r,n){var o=r.shift();if("__proto__"===o||"prototype"===o)return t;if(r.length>0)t[o]=e(t[o]||{},r,n);else{var s=t[o];s&&(n=[].concat(s).concat(n)),t[o]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(s,"decorateRoot",{get:function(){return i.decorated||(i.decorated=new(r(5330)))}})},2239:(e,t,r)=>{"use strict";e.exports=o;var n=r(3610);function o(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=o.zero=new o(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var i=o.zeroHash="\0\0\0\0\0\0\0\0";o.fromNumber=function(e){if(0===e)return s;var t=e<0;t&&(e=-e);var 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 o(r,n)},o.from=function(e){if("number"==typeof e)return o.fromNumber(e);if(n.isString(e)){if(!n.Long)return o.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new o(e.low>>>0,e.high>>>0):s},o.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},o.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;o.fromHash=function(e){return e===i?s:new o((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},o.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},o.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},o.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},o.prototype.length=function(){var 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}},3610:function(e,t,r){"use strict";var n=t;function o(e,t,r){for(var n=Object.keys(t),o=0;o<n.length;++o)void 0!==e[n[o]]&&r||(e[n[o]]=t[n[o]]);return e}function s(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&o(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=r(8045),n.base64=r(8839),n.EventEmitter=r(4358),n.float=r(9410),n.inquire=r(4153),n.utf8=r(1447),n.pool=r(9390),n.LongBits=r(2239),n.isNode=Boolean("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),n.global=n.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"==typeof e||e instanceof String},n.isObject=function(e){return e&&"object"==typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=o,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=s,n.ProtocolError=s("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},n.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},n._configure=function(){var e=n.Buffer;e?(n._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},n._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):n._Buffer_from=n._Buffer_allocUnsafe=null}},420:(e,t,r)=>{"use strict";e.exports=function(e){var t=o.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n<e.fieldsArray.length;++n){var c=e._fieldsArray[n].resolve(),l="m"+o.safeProp(c.name);if(c.optional&&t("if(%s!=null&&m.hasOwnProperty(%j)){",l,c.name),c.map)t("if(!util.isObject(%s))",l)("return%j",s(c,"object"))("var k=Object.keys(%s)",l)("for(var i=0;i<k.length;++i){"),a(t,c,"k[i]"),i(t,c,n,l+"[k[i]]")("}");else if(c.repeated)t("if(!Array.isArray(%s))",l)("return%j",s(c,"array"))("for(var i=0;i<%s.length;++i){",l),i(t,c,n,l+"[i]")("}");else{if(c.partOf){var u=o.safeProp(c.partOf.name);1===r[c.partOf.name]&&t("if(p%s===1)",u)("return%j",c.partOf.name+": multiple values"),r[c.partOf.name]=1,t("p%s=1",u)}i(t,c,n,l)}c.optional&&t("}")}return t("return null")};var n=r(5643),o=r(3262);function s(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function i(e,t,r,o){if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(%s){",o)("default:")("return%j",s(t,"enum value"));for(var i=Object.keys(t.resolvedType.values),a=0;a<i.length;++a)e("case %i:",t.resolvedType.values[i[a]]);e("break")("}")}else e("{")("var e=types[%i].verify(%s);",r,o)("if(e)")("return%j+e",t.name+".")("}");else switch(t.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.isInteger(%s))",o)("return%j",s(t,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",o,o,o,o)("return%j",s(t,"integer|Long"));break;case"float":case"double":e('if(typeof %s!=="number")',o)("return%j",s(t,"number"));break;case"bool":e('if(typeof %s!=="boolean")',o)("return%j",s(t,"boolean"));break;case"string":e("if(!util.isString(%s))",o)("return%j",s(t,"string"));break;case"bytes":e('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',o,o,o)("return%j",s(t,"buffer"))}return e}function a(e,t,r){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",r)("return%j",s(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",r)("return%j",s(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",r)("return%j",s(t,"boolean key"))}return e}},6434:(e,t,r)=>{"use strict";var n=t,o=r(2551);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var s=this.lookup(n);s&&(e=s.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof o){var i=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),i["@type"]=n,i}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,o=r(3610),s=o.LongBits,i=o.base64,a=o.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return o.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function p(e,t,r){t[r]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;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 m(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new o.Array(e)},o.Array!==Array&&(h.alloc=o.pool(h.alloc,o.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},f.prototype=Object.create(c.prototype),f.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,s.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=s.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=s.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(p,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(m,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=s.from(e);return this._push(m,4,t.lo)._push(m,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(o.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(o.float.writeDoubleLE,8,e)};var y=o.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n<e.length;++n)t[r+n]=e[n]};h.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(p,1,0);if(o.isString(e)){var r=h.alloc(t=i.length(e));i.decode(e,r,0),e=r}return this.uint32(t)._push(y,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},818:(e,t,r)=>{"use strict";e.exports=s;var n=r(3449);(s.prototype=Object.create(n.prototype)).constructor=s;var o=r(3610);function s(){n.call(this)}function i(e,t,r){e.length<40?o.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}s._configure=function(){s.alloc=o._Buffer_allocUnsafe,s.writeBytesBuffer=o.Buffer&&o.Buffer.prototype instanceof Uint8Array&&"set"===o.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n<e.length;)t[r++]=e[n++]}},s.prototype.bytes=function(e){o.isString(e)&&(e=o._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=o.Buffer.byteLength(e);return this.uint32(t),t&&this._push(i,t,e),this},s._configure()},152:(e,t)=>{"use strict";class r{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let e=0;e<n.length;e++)if(n[e]!==o[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(const e of t)r+=e.byteLength;const n=new Uint8Array(r);let o=0;for(const e of t){const t=this.toUint8Array(e);n.set(t,o),o+=t.length}return e[e.length-1]instanceof Function?this.toView(n,e[e.length-1]):n.buffer}}const n="string",o=/^[0-9a-f\s]+$/i,s=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i=/^[a-zA-Z0-9-_]+$/;class a{static fromString(e){const t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){const t=r.toUint8Array(e);let n="";for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return decodeURIComponent(escape(n))}}class c{static toString(e,t=!1){const n=r.toArrayBuffer(e),o=new DataView(n);let s="";for(let e=0;e<n.byteLength;e+=2){const r=o.getUint16(e,t);s+=String.fromCharCode(r)}return s}static fromString(e,t=!1){const r=new ArrayBuffer(2*e.length),n=new DataView(r);for(let r=0;r<e.length;r++)n.setUint16(2*r,e.charCodeAt(r),t);return r}}class l{static isHex(e){return typeof e===n&&o.test(e)}static isBase64(e){return typeof e===n&&s.test(e)}static isBase64Url(e){return typeof e===n&&i.test(e)}static ToString(e,t="utf8"){const n=r.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return c.toString(n,!0);case"utf16":case"utf16be":return c.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return c.fromString(e,!0);case"utf16":case"utf16be":return c.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=r.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!l.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!l.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=l.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return a.fromString(e);case"utf16":case"utf16be":return c.fromString(e);case"utf16le":case"usc2":return c.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=l.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return a.toString(e);case"utf16":case"utf16be":return c.toString(e);case"utf16le":case"usc2":return c.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(e){const t=r.toUint8Array(e);let n="";for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return n}static ToHex(e){const t=r.toUint8Array(e);let n="";const o=t.length;for(let e=0;e<o;e++){const r=t[e];r<16&&(n+="0"),n+=r.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!l.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const n=t.slice(e,e+2);r[e/2]=parseInt(n,16)}return r.buffer}static ToUtf16String(e,t=!1){return c.toString(e,t)}static FromUtf16String(e,t=!1){return c.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}l.DEFAULT_UTF8_ENCODING="utf8",t._H=r,t.U$=l},5617:(e,t,r)=>{e.exports=r(8303)},8303:(e,t,r)=>{var n=r(3961);t.operation=function(e){var r=t.timeouts(e);return new n(r,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort((function(e,t){return e-t})),n},t.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},t.wrap=function(e,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var o in n=[],e)"function"==typeof e[o]&&n.push(o);for(var s=0;s<n.length;s++){var i=n[s],a=e[i];e[i]=function(n){var o=t.operation(r),s=Array.prototype.slice.call(arguments,1),i=s.pop();s.push((function(e){o.retry(e)||(e&&(arguments[0]=o.mainError()),i.apply(this,arguments))})),o.attempt((function(){n.apply(e,s)}))}.bind(e,a),e[i].options=r}}},3961:e=>{function t(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(e[s]||0)+1;e[s]=i,i>=r&&(t=o,r=i)}return t}},495:()=>{}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var o=2&t&&e;"object"==typeof o&&!~leafPrototypes.indexOf(o);o=getProto(o))Object.getOwnPropertyNames(o).forEach((t=>n[t]=()=>e[t]));return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>ne});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>oe,base16upper:()=>se});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>ie});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>ue});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base32:()=>he,base32hex:()=>ge,base32hexpad:()=>ye,base32hexpadupper:()=>be,base32hexupper:()=>me,base32pad:()=>pe,base32padupper:()=>fe,base32upper:()=>de,base32z:()=>we});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base36:()=>ve,base36upper:()=>Ee});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base58btc:()=>Se,base58flickr:()=>Ae});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>ke,base64pad:()=>Ce,base64url:()=>Ie,base64urlpad:()=>xe});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>Te});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>_e});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Be,decode:()=>Re,encode:()=>Oe,name:()=>Le});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>Ue,decode:()=>Fe,encode:()=>Me,name:()=>De});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>ct});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>dt,sha512:()=>pt});var f={};function g(e=0){return new Uint8Array(e)}function m(e=0){return new Uint8Array(e)}__webpack_require__.r(f),__webpack_require__.d(f,{aK:()=>Xi,e8:()=>Oi,DO:()=>Bi,dJ:()=>Yi,OG:()=>Zi,My:()=>Di,Ph:()=>Hi,lX:()=>ji,Id:()=>Gi,fg:()=>ta,qj:()=>Ki,aT:()=>qi,r4:()=>Ji,aY:()=>Li,x:()=>oa,lq:()=>Vi,z:()=>zi,zW:()=>Ui,Q5:()=>na});const y=Math.pow(2,7),b=Math.pow(2,14),w=Math.pow(2,21),v=Math.pow(2,28),E=Math.pow(2,35),S=Math.pow(2,42),A=Math.pow(2,49),k=128,C=127;function I(e){if(e<y)return 1;if(e<b)return 2;if(e<w)return 3;if(e<v)return 4;if(e<E)return 5;if(e<S)return 6;if(e<A)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function x(e,t,r=0){switch(I(e)){case 8:t[r++]=255&e|k,e/=128;case 7:t[r++]=255&e|k,e/=128;case 6:t[r++]=255&e|k,e/=128;case 5:t[r++]=255&e|k,e/=128;case 4:t[r++]=255&e|k,e>>>=7;case 3:t[r++]=255&e|k,e>>>=7;case 2:t[r++]=255&e|k,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function T(e,t){let r=e[t],n=0;if(n+=r&C,r<k)return n;if(r=e[t+1],n+=(r&C)<<7,r<k)return n;if(r=e[t+2],n+=(r&C)<<14,r<k)return n;if(r=e[t+3],n+=(r&C)<<21,r<k)return n;if(r=e[t+4],n+=(r&C)*v,r<k)return n;if(r=e[t+5],n+=(r&C)*E,r<k)return n;if(r=e[t+6],n+=(r&C)*S,r<k)return n;if(r=e[t+7],n+=(r&C)*A,r<k)return n;throw new RangeError("Could not decode varint")}function _(e,t,r=0){return null==t&&(t=m(I(e))),t instanceof Uint8Array?x(e,t,r):function(e,t,r=0){switch(I(e)){case 8:t.set(r++,255&e|k),e/=128;case 7:t.set(r++,255&e|k),e/=128;case 6:t.set(r++,255&e|k),e/=128;case 5:t.set(r++,255&e|k),e/=128;case 4:t.set(r++,255&e|k),e>>>=7;case 3:t.set(r++,255&e|k),e>>>=7;case 2:t.set(r++,255&e|k),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function N(e,t=0){return e instanceof Uint8Array?T(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&C,r<k)return n;if(r=e.get(t+1),n+=(r&C)<<7,r<k)return n;if(r=e.get(t+2),n+=(r&C)<<14,r<k)return n;if(r=e.get(t+3),n+=(r&C)<<21,r<k)return n;if(r=e.get(t+4),n+=(r&C)*v,r<k)return n;if(r=e.get(t+5),n+=(r&C)*E,r<k)return n;if(r=e.get(t+6),n+=(r&C)*S,r<k)return n;if(r=e.get(t+7),n+=(r&C)*A,r<k)return n;throw new RangeError("Could not decode varint")}(e,t)}const P=new Float32Array([-0]),L=new Uint8Array(P.buffer);function B(e,t,r){P[0]=e,t[r]=L[0],t[r+1]=L[1],t[r+2]=L[2],t[r+3]=L[3]}const O=new Float64Array([-0]),R=new Uint8Array(O.buffer);function D(e,t,r){O[0]=e,t[r]=R[0],t[r+1]=R[1],t[r+2]=R[2],t[r+3]=R[3],t[r+4]=R[4],t[r+5]=R[5],t[r+6]=R[6],t[r+7]=R[7]}const U=BigInt(Number.MAX_SAFE_INTEGER),M=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){const e=1+~this.lo>>>0;let 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){const e=1+~this.lo>>>0;let 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(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const 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 $;if(e<U&&e>M)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>q&&(n=0n,++r>q&&(r=0n))),new F(Number(n),Number(r))}static fromNumber(e){if(0===e)return $;const 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):$}}const $=new F(0,0);$.toBigInt=function(){return 0n},$.zzEncode=$.zzDecode=function(){return this},$.length=function(){return 1};const q=4294967296n;function H(e,t,r){const n=r;let o,s;for(let n=0;n<e.length;++n)o=e.charCodeAt(n),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&56320==(64512&(s=e.charCodeAt(n+1)))?(o=65536+((1023&o)<<10)+(1023&s),++n,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128);return r-n}function j(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 z{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)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(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,j(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw j(this,4);return V(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw j(this,4);return 0|V(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw j(this,4);const e=(t=this.buf,r=this.pos,L[0]=t[r],L[1]=t[r+1],L[2]=t[r+2],L[3]=t[r+3],P[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw j(this,4);const e=(t=this.buf,r=this.pos,R[0]=t[r],R[1]=t[r+1],R[2]=t[r+2],R[3]=t[r+3],R[4]=t[r+4],R[5]=t[r+5],R[6]=t[r+6],R[7]=t[r+7],O[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw j(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const o=[];let s,i=0;for(;t<r;)s=e[t++],s<128?o[i++]=s:s>191&&s<224?o[i++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(s>>10),o[i++]=56320+(1023&s)):o[i++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return null!=n?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw j(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw j(this)}while(128&this.buf[this.pos++]);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(){const e=new F(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw j(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}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;if(t=0,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 j(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 j(this,8);const e=V(this.buf,this.pos+=4),t=V(this.buf,this.pos+=4);return new F(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=T(this.buf,this.pos);return this.pos+=I(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 K(e,t,r){const n=function(e){return new z(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function G(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}new Uint8Array(0);const W=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(255!==r[i])throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,o=0;e[t]===c;)n++,t++;for(var s=(e.length-t)*l+1>>>0,i=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<o)&&-1!==d;d--,h++)u+=a*i[d]>>>0,i[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");o=h,t++}if(" "!==e[t]){for(var p=s-o;p!==s&&0===i[p];)p++;for(var f=new Uint8Array(n+(s-p)),g=n;p!==s;)f[g++]=i[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 new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,o=0,s=t.length;o!==s&&0===t[o];)o++,r++;for(var i=(s-o)*u+1>>>0,l=new Uint8Array(i);o!==s;){for(var h=t[o],d=0,p=i-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,o++}for(var f=i-n;f!==i&&0===l[f];)f++;for(var g=c.repeat(r);f<i;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var r=h(e);if(r)return r;throw new Error(`Non-${t} character`)}}};class J{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class X{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Z(this,e)}}class Y{decoders;constructor(e){this.decoders=e}or(e){return Z(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Z(e,t){return new Y({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class Q{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new J(e,t,r),this.decoder=new X(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function ee({name:e,prefix:t,encode:r,decode:n}){return new Q(e,t,r,n)}function te({name:e,prefix:t,alphabet:r}){const{encode:n,decode:o}=W(r,e);return ee({prefix:t,name:e,encode:n,decode:e=>G(o(e))})}function re({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return ee({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],o=(1<<r)-1;let s="",i=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(0!==i&&(s+=t[o&a<<r-i]),n)for(;s.length*r&7;)s+="=";return s}(e,n,r),decode:t=>function(e,t,r,n){const o={};for(let e=0;e<t.length;++e)o[t[e]]=e;let s=e.length;for(;"="===e[s-1];)--s;const i=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let t=0;t<s;++t){const s=o[e[t]];if(void 0===s)throw new SyntaxError(`Non-${n} character`);c=c<<r|s,a+=r,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}(t,n,r,e)})}const ne=te({prefix:"9",name:"base10",alphabet:"0123456789"}),oe=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),se=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),ie=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ae=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ce=ae.reduce(((e,t,r)=>(e[r]=t,e)),[]),le=ae.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e}),[]),ue=ee({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+ce[t]),"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=le[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}}),he=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),de=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),pe=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fe=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ge=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),me=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ye=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),be=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),we=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ve=te({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ee=te({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Se=te({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ae=te({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),ke=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ce=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ie=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xe=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Te=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),_e=ee({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),Ne=new TextEncoder,Pe=new TextDecoder,Le="json",Be=512;function Oe(e){return Ne.encode(JSON.stringify(e))}function Re(e){return JSON.parse(Pe.decode(e))}const De="raw",Ue=85;function Me(e){return G(e)}function Fe(e){return G(e)}var $e=128,qe=-128,He=Math.pow(2,31),je=128,Ve=127,ze=Math.pow(2,7),Ke=Math.pow(2,14),Ge=Math.pow(2,21),We=Math.pow(2,28),Je=Math.pow(2,35),Xe=Math.pow(2,42),Ye=Math.pow(2,49),Ze=Math.pow(2,56),Qe=Math.pow(2,63);const et={encode:function e(t,r,n){r=r||[];for(var o=n=n||0;t>=He;)r[n++]=255&t|$e,t/=128;for(;t&qe;)r[n++]=255&t|$e,t>>>=7;return r[n]=0|t,e.bytes=n-o+1,r},decode:function e(t,r){var n,o=0,s=0,i=r=r||0,a=t.length;do{if(i>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[i++],o+=s<28?(n&Ve)<<s:(n&Ve)*Math.pow(2,s),s+=7}while(n>=je);return e.bytes=i-r,o},encodingLength:function(e){return e<ze?1:e<Ke?2:e<Ge?3:e<We?4:e<Je?5:e<Xe?6:e<Ye?7:e<Ze?8:e<Qe?9:10}};function tt(e,t=0){return[et.decode(e,t),et.decode.bytes]}function rt(e,t,r=0){return et.encode(e,t,r),t}function nt(e){return et.encodingLength(e)}function ot(e,t){const r=t.byteLength,n=nt(e),o=n+nt(r),s=new Uint8Array(o+r);return rt(e,s,0),rt(r,s,n),s.set(t,o),new it(e,r,t,s)}function st(e){const t=G(e),[r,n]=tt(t),[o,s]=tt(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new it(r,o,i,t)}class it{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const at=G,ct={code:0,name:"identity",encode:at,digest:function(e){return ot(0,at(e))}};function lt({name:e,code:t,encode:r}){return new ut(e,t,r)}class ut{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ot(this.code,t):t.then((e=>ot(this.code,e)))}throw Error("Unknown type, must be binary type")}}function ht(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const dt=lt({name:"sha2-256",code:18,encode:ht("SHA-256")}),pt=lt({name:"sha2-512",code:19,encode:ht("SHA-512")});function ft(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Se.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=t.get(n);if(null==o){const o=r.encode(e).slice(1);return t.set(n,o),o}return o}(r,mt(e),t??Se.encoder):function(e,t,r){const{prefix:n}=r,o=t.get(n);if(null==o){const o=r.encode(e);return t.set(n,o),o}return o}(r,mt(e),t??he.encoder)}const gt=new WeakMap;function mt(e){const t=gt.get(e);if(null==t){const t=new Map;return gt.set(e,t),t}return t}class yt{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==bt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wt)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return yt.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=ot(e,t);return yt.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return yt.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return ft(this,e)}toJSON(){return{"/":ft(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof yt)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:o}=t;return new yt(e,r,n,o??vt(e,r,n.bytes))}if(!0===t[Et]){const{version:e,multihash:r,code:n}=t,o=st(r);return yt.create(e,n,o)}return null}static create(e,t,r){if("number"!=typeof t)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:if(t!==bt)throw new Error(`Version 0 CID must use dag-pb (code: ${bt}) block encoding`);return new yt(e,t,r,r.bytes);case 1:{const n=vt(e,t,r.bytes);return new yt(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return yt.create(0,bt,e)}static createV1(e,t){return yt.create(1,e,t)}static decode(e){const[t,r]=yt.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=yt.inspectBytes(e),r=t.size-t.multihashSize,n=G(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");const o=n.subarray(t.multihashSize-t.digestSize),s=new it(t.multihashCode,t.digestSize,o,n);return[0===t.version?yt.createV0(s):yt.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=tt(e.subarray(t));return t+=n,r};let n=r(),o=bt;if(18===n?(n=0,t=0):o=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const s=t,i=r(),a=r(),c=t+a;return{version:n,codec:o,multihashCode:i,digestSize:a,multihashSize:c-s,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??Se;return[Se.prefix,r.decode(`${Se.prefix}${e}`)]}case Se.prefix:{const r=t??Se;return[Se.prefix,r.decode(e)]}case he.prefix:{const r=t??he;return[he.prefix,r.decode(e)]}case ve.prefix:{const r=t??ve;return[ve.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),o=yt.decode(n);if(0===o.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return mt(o).set(r,e),o}}const bt=112,wt=18;function vt(e,t,r){const n=nt(e),o=n+nt(t),s=new Uint8Array(o+r.byteLength);return rt(e,s,0),rt(t,s,n),s.set(r,o),s}const Et=Symbol.for("@ipld/js-cid/CID"),St={...l,...r,...c,...e,...t,...o,...s,...i,...a,...n};function At(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const kt=At("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ct=At("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=m((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),It={utf8:kt,"utf-8":kt,hex:St.base16,latin1:Ct,ascii:Ct,binary:Ct,...St};function xt(e,t="utf8"){const r=It[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class Tt{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function _t(){}class Nt{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Pt=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return m(n);r+n>e&&(t=m(e),r=0);const o=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),o}}();class Lt{len;head;tail;states;constructor(){this.len=0,this.head=new Tt(_t,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Tt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Rt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Dt,10,F.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=F.fromBigInt(e);return this._push(Dt,t.length(),t)}uint64Number(e){return this._push(x,I(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){const t=F.fromBigInt(e).zzEncode();return this._push(Dt,t.length(),t)}sint64Number(e){const t=F.fromNumber(e).zzEncode();return this._push(Dt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Bt,1,e?1:0)}fixed32(e){return this._push(Ut,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=F.fromBigInt(e);return this._push(Ut,4,t.lo)._push(Ut,4,t.hi)}fixed64Number(e){const t=F.fromNumber(e);return this._push(Ut,4,t.lo)._push(Ut,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(B,4,e)}double(e){return this._push(D,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Bt,1,0):this.uint32(t)._push(Mt,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(H,t,e):this._push(Bt,1,0)}fork(){return this.states=new Nt(this),this.head=this.tail=new Tt(_t,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Tt(_t,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?m(r):Pt(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function Bt(e,t,r){t[r]=255&e}function Ot(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Rt extends Tt{next;constructor(e,t){super(Ot,e,t),this.next=void 0}}function Dt(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 Ut(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 Mt(e,t,r){t.set(e,r)}function Ft(e,t,r){t.set(e,r)}function $t(e,t,r){e.length<40?H(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(xt(e),r)}function qt(e,t){const r=new Lt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var Ht,jt,Vt,zt,Kt,Gt,Wt,Jt,Xt,Yt,Zt,Qt,er,tr,rr,nr,or,sr,ir,ar,cr,lr,ur,hr,dr,pr,fr,gr,mr,yr;function br(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function wr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return br("enum",Ht.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function vr(e,t){return br("message",Ht.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Lt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Ft,t,e),this},Lt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push($t,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(Ht||(Ht={})),Error;class Er extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Sr extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function Ar(e){return Boolean(e)}function kr(e){const t=new Map;return e.forEach((e=>{let r=t.get(e.contentTopic);r||(t.set(e.contentTopic,[]),r=t.get(e.contentTopic)),r.push(e)})),t}function Cr(e){return new Promise((t=>{setTimeout(t,e)}))}!function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={proof:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(jt||(jt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),jt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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=jt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Vt||(Vt={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();t>>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const o={subscribe:!1,topic:"",contentFilters:[]},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:o.subscribe=t.bool();break;case 2:o.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&o.contentFilters.length===n.limits.contentFilters)throw new Er('Decode error - map field "contentFilters" had too many elements');o.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return o}))),r),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(zt||(zt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),Jt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Er('Decode error - map field "messages" had too many elements');n.messages.push(Jt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Kt||(Kt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),zt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),Kt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=zt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=Kt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Gt||(Gt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={proof:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Wt||(Wt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),Wt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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=Wt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Jt||(Jt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();t>>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Xt||(Xt={})),function(e){let t,r,n;!function(e){e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),function(e){e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(r||(r={})),function(e){e.codec=()=>wr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=vr(((t,n,o={})=>{if(!1!==o.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==o.lengthDelimited&&n.ldelim()}),((r,n,o={})=>{const s={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},i=null==n?r.len:r.pos+n;for(;r.pos<i;){const t=r.uint32();switch(t>>>3){case 1:s.requestId=r.string();break;case 2:s.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:s.pubsubTopic=r.string();break;case 11:if(null!=o.limits?.contentTopics&&s.contentTopics.length===o.limits.contentTopics)throw new Er('Decode error - map field "contentTopics" had too many elements');s.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return s}))),n),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Yt||(Yt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={requestId:"",statusCode:0},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Zt||(Zt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),tr.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=tr.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Qt||(Qt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={proof:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(er||(er={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),er.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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=er.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(tr||(tr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),ir.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=ir.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(rr||(rr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={isSuccess:!1},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(nr||(nr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),rr.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),nr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=rr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=nr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(or||(or={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={proof:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(sr||(sr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),sr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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=sr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ir||(ir={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),hr.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=hr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new Er('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new Er('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(cr||(cr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),ar.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Er('Decode error - map field "messages" had too many elements');n.messages.push(ar.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={proof:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),ur.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>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=ur.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();t>>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();t>>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),dr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new Er('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(dr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(fr||(fr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),pr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),fr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.query=pr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=fr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Er('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Er('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(yr||(yr={}));function Ir(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function xr(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Tr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Ir(e.outputLen),Ir(e.blockLen)}function _r(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Nr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Lr(e,t){return e<<32-t|e>>>t}function Br(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),xr(e),e}class Or{clone(){return this._cloneInto()}}function Rr(e){const t=t=>e().update(Br(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Dr(e=32){if(Nr&&"function"==typeof Nr.getRandomValues)return Nr.getRandomValues(new Uint8Array(e));if(Nr&&"function"==typeof Nr.randomBytes)return Nr.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function Ur(e,t,r){return e&t^e&r^t&r}class Mr extends Or{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Pr(this.buffer)}update(e){_r(this);const{view:t,buffer:r,blockLen:n}=this,o=(e=Br(e)).length;for(let s=0;s<o;){const i=Math.min(n-this.pos,o-s);if(i!==n)r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=Pr(e);for(;n<=o-s;s+=n)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){_r(this),function(e,t){xr(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:o}=this;let{pos:s}=this;t[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>n-s&&(this.process(r,0),s=0);for(let e=s;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),o),this.process(r,0);const i=Pr(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,l[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.length=n,e.pos=i,e.finished=o,e.destroyed=s,n%t&&e.buffer.set(r),e}}const Fr=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$r=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qr=new Uint32Array(64);class Hr extends Mr{constructor(){super(64,32,8,!1),this.A=0|$r[0],this.B=0|$r[1],this.C=0|$r[2],this.D=0|$r[3],this.E=0|$r[4],this.F=0|$r[5],this.G=0|$r[6],this.H=0|$r[7]}get(){const{A:e,B:t,C:r,D:n,E:o,F:s,G:i,H:a}=this;return[e,t,r,n,o,s,i,a]}set(e,t,r,n,o,s,i,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|o,this.F=0|s,this.G=0|i,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)qr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=qr[e-15],r=qr[e-2],n=Lr(t,7)^Lr(t,18)^t>>>3,o=Lr(r,17)^Lr(r,19)^r>>>10;qr[e]=o+qr[e-7]+n+qr[e-16]|0}let{A:r,B:n,C:o,D:s,E:i,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Lr(i,6)^Lr(i,11)^Lr(i,25))+((u=i)&a^~u&c)+Fr[e]+qr[e]|0,h=(Lr(r,2)^Lr(r,13)^Lr(r,22))+Ur(r,n,o)|0;l=c,c=a,a=i,i=s+t|0,s=o,o=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,s=s+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,s,i,a,c,l)}roundClean(){qr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const jr=Rr((()=>new Hr));var Vr,zr,Kr,Gr,Wr;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(Vr||(Vr={})),function(e){e.GENERIC_FAIL="Generic error",e.ENCODE_FAILED="Failed to encode",e.DECODE_FAILED="Failed to decode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout",e.RLN_IDENTITY_MISSING="Identity credentials are not set",e.RLN_MEMBERSHIP_INDEX="Membership index is not set",e.RLN_LIMIT_MISSING="User message limit is not set",e.RLN_PROOF_GENERATION="Proof generation failed"}(zr||(zr={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(Kr||(Kr={})),function(e){e.PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",e.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",e.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",e.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange"}(Gr||(Gr={})),function(e){e.CONNECTION_STATUS="waku:connection"}(Wr||(Wr={}));const Jr="@waku/bootstrap",Xr={clusterId:1,shards:[0,1,2,3,4,5,6,7,8]};var Yr;function Zr(e,t="utf8"){const r=It[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function Qr(e){return"string"==typeof e?xt(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}!function(e){e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"}(Yr||(Yr={}));const en=e=>Zr(e,"base16"),tn=e=>Zr(e,"utf8"),rn=e=>xt(e,"utf8");function nn(e,t){const r=t??e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(r);let o=0;for(const t of e)n.set(t,o),o+=t.length;return n}const on=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map((t=>ln(t,e.clusterId)))));if("shards"in e){if(void 0===e.shards)throw new Error("Invalid shard");return Array.from(new Set(e.shards.map((t=>`/waku/2/rs/${e.clusterId??1}/${t}`))))}if("application"in e&&"version"in e)return[ln(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw new Error("Missing required configuration in shard parameters")},sn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw new Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw new Error("Invalid clusterId or shard");return{clusterId:r,shard:n}},an=e=>{const t=new Set,r=new Set;for(const n of e){const{clusterId:e,shard:o}=sn(n);t.add(`${e}:${o}`),r.add(e)}if(0===t.size)throw new Error("No valid pubsub topics provided");if(r.size>1)throw new Error("Pubsub topics from multiple cluster IDs are not supported");return{clusterId:r.values().next().value,shards:Array.from(t).map((e=>parseInt(e.split(":")[1])))}};function cn(e,t){if(!t.includes(e))throw new 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 ln(e,t=1,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${function(e,t=8){const{application:r,version:n}=function(e){const 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(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),o=jr(nn([rn(r),rn(n)])),s=new DataView(o.buffer.slice(-8));return Number(s.getBigUint64(0,!1)%BigInt(t))}(e,r)}`}function un(e,t){return"string"==typeof t?t:void 0!==t?.shard?(e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??1}/${e.shard}`})(t):ln(e,t?.clusterId??1)}const hn=e=>{if((e=new Uint8Array(e)).length<3)throw new Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,o=7-e%8;t.getUint8(r)&1<<o&&n.push(e)}else{const r=t.getUint8(2);for(let o=0,s=3;o<r;o++,s+=2){if(s+1>=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(s))}}return{clusterId:r,shards:n}},dn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,o=new ArrayBuffer(n),s=new DataView(o);if(s.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;s.setUint8(t,s.getUint8(t)|1<<r)}else{s.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)s.setUint16(t,r[e])}return new Uint8Array(o)};var pn=__webpack_require__(7833);const fn="waku";class gn{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${fn}:${e}:${t}`:`${fn}:${e}`}constructor(e){this._info=pn(gn.createDebugNamespace("info",e)),this._warn=pn(gn.createDebugNamespace("warn",e)),this._error=pn(gn.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)}}const mn=new gn("message:version-0"),yn=BigInt(1e6);class bn{pubsubTopic;proto;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return Boolean(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){const e=this.proto.timestamp/yn;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 wn{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 new Error("Content topic must be specified")}async toWire(e){return Vt.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*yn,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}}function vn({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:o}){return new wn(r,n,un(r,e??t),o)}class En{pubsubTopic;contentTopic;constructor(e,t){if(this.pubsubTopic=e,this.contentTopic=t,!t||""===t)throw new Error("Content topic must be specified")}fromWireToProtoObj(e){const t=Vt.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?(mn.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new bn(e,t)}}function Sn(e,t){return new En(un(e,t),e)}const An=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t};function kn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=m(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Cn(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}const In=Symbol.for("@achingbrain/uint8arraylist");function xn(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function Tn(e){return Boolean(e?.[In])}class _n{bufs;length;[In]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!Tn(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!Tn(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=xn(this.bufs,e);return t.buf[t.index]}set(e,t){const r=xn(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!Tn(e))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return kn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:kn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),o=new _n;return o.length=n,o.bufs=[...r],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let o=0;o<this.bufs.length;o++){const s=this.bufs[o],i=n,a=i+s.byteLength;if(n=a,e>=a)continue;const c=e>=i&&e<a,l=t>i&&t<=a;if(c&&l){if(e===i&&t===a){r.push(s);break}const n=e-i;r.push(s.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(s);continue}r.push(s.subarray(e-i))}else{if(l){if(t===a){r.push(s);break}r.push(s.subarray(0,t-i));break}r.push(s)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Tn(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const o=new Int32Array(256);for(let e=0;e<256;e++)o[e]=-1;for(let e=0;e<n;e++)o[r[e]]=e;const s=o,i=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=i;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-s[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=m(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=g(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=g(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=g(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=m(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=g(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=g(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=g(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=g(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=g(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof _n))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Cn(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new _n;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function Nn(e){return null!=e[Symbol.asyncIterator]}const Pn=e=>{const t=I(e),r=m(t);return _(e,r),Pn.bytes=t,r};function Ln(e,t){const r=(t=t??{}).lengthEncoder??Pn;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Nn(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Pn.bytes=0,Ln.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Pn;return new _n(r(e.byteLength),e)};class Bn extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class On extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Rn extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class Dn extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}var Un;!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Un||(Un={}));const Mn=e=>{const t=N(e);return Mn.bytes=I(t),t};function Fn(e,t){const r=new _n;let n=Un.LENGTH,o=-1;const s=t?.lengthDecoder??Mn,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Un.LENGTH)try{if(o=s(r),o<0)throw new Bn("Invalid message length");if(o>a)throw new On("Message length too long");const e=s.bytes;r.consume(e),null!=t?.onLength&&t.onLength(o),n=Un.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>i)throw new Rn("Message length length too long");break}throw e}if(n===Un.DATA){if(r.byteLength<o)break;const e=r.sublist(0,o);r.consume(o),null!=t?.onData&&t.onData(e),yield e,n=Un.LENGTH}}}return Nn(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Dn("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Dn("Unexpected end of input")}()}function $n(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Mn.bytes=0,Fn.fromReader=(e,t)=>{let r=1;return Fn(async function*(){for(;;)try{const{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}})};class qn{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const 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 Hn{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new qn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new qn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class jn extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Vn(e={}){return function(e,t){let r,n,o,s=(t=t??{}).onEnd,i=new Hn,a=$n();const c=e=>null!=n?n(e):(i.push(e),r),l=e=>{if(o)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>o?r:(o=!0,null!=e?(e=>(i=new Hn,null!=n?n({error:e}):(i.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return i.isEmpty()?o?{done:!0}:await new Promise(((t,o)=>{n=s=>{n=null,i.push(s);try{t(e(i))}catch(e){o(e)}return r}})):e(i)}finally{i.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=$n()}))}},return:()=>(i=new Hn,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return i.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),i.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new jn)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==s)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=s&&(s(e),s=void 0),{done:!0}),return:()=>(h.return(),null!=s&&(s(),s=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=s&&(s(e),s=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const 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)}const zn=function(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(){for(const e of t)yield*e}():async function*(){const t=Vn({objectMode:!0});Promise.resolve().then((async()=>{try{await Promise.all(e.map((async e=>{for await(const r of e)t.push(r)}))),t.end()}catch(e){t.end(e)}})),yield*t}()};function Kn(e,...t){if(null==e)throw new Error("Empty pipeline");if(Xn(e)){const t=e;e=()=>t.source}else if(Jn(e)||Wn(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&Xn(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)Xn(r[e])&&(r[e]=Yn(r[e]));return Gn(...r)}const Gn=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},Wn=e=>null!=e?.[Symbol.asyncIterator],Jn=e=>null!=e?.[Symbol.iterator],Xn=e=>null!=e&&null!=e.sink&&null!=e.source,Yn=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Vn({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const o=e.source;if(Wn(o))n=async function*(){yield*o,t.end()};else{if(!Jn(o))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*o,t.end()}}return zn(t,n())}return e.source};function Zn(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const Qn="consumed";class eo{multicodec;getConnections;addEventListener;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new gn(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e.id);return n?(this.log.info(`Found existing stream peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.lockStream(e.id.toString(),n),n):(n=await this.createStream(e),this.lockStream(e.id.toString(),n),n)}async createStream(e,t=0){const r=Zn(this.getConnections(e.id));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.id.toString()} multicodec=${this.multicodec}`);let n,o;for(let s=0;s<t+1;s++)try{this.log.info(`Attempting to create a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),o=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(!o)throw new Error(`Failed to create a new stream for ${e.id.toString()} -- `+n);return o}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=Zn(this.getConnections(e));if(!t)return;const r=t.streams.find((e=>e.protocol===this.multicodec));return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[Qn]=!0}isStreamLocked(e){return!!e.metadata[Qn]}}class to{multicodec;components;pubsubTopics;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r){this.multicodec=e,this.components=t,this.pubsubTopics=r,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new eo(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}}const ro={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let no;const oo=new Uint8Array(16);function so(){if(!no&&(no="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!no))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return no(oo)}const io=[];for(let e=0;e<256;++e)io.push((e+256).toString(16).slice(1));const ao=function(e,t,r){if(ro.randomUUID&&!t&&!e)return ro.randomUUID();const n=(e=e||{}).random||(e.rng||so)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return io[e[t+0]]+io[e[t+1]]+io[e[t+2]]+io[e[t+3]]+"-"+io[e[t+4]]+io[e[t+5]]+"-"+io[e[t+6]]+io[e[t+7]]+"-"+io[e[t+8]]+io[e[t+9]]+"-"+io[e[t+10]]+io[e[t+11]]+io[e[t+12]]+io[e[t+13]]+io[e[t+14]]+io[e[t+15]]}(n)};class co{proto;constructor(e){this.proto=e}static decode(e){const t=Qt.decode(e);return new co(t)}encode(){return Qt.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class lo{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=Yt.decode(e);return new lo(t)}encode(){return Yt.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 uo{proto;constructor(e){this.proto=e}static decode(e){const t=Zt.decode(e);return new uo(t)}encode(){return Zt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const ho=new gn("filter:v2"),po="/vac/waku/filter-subscribe/2.0.0-beta1",fo="/vac/waku/filter-push/2.0.0-beta1";class go extends to{handleIncomingMessage;pubsubTopics;constructor(e,t,r){super(po,r.components,t),this.handleIncomingMessage=e,this.pubsubTopics=t,r.handle(fo,this.onRequest.bind(this),{maxInboundStreams:100}).catch((e=>{ho.error("Failed to register ",fo,e)}))}async subscribe(e,t,r){const n=await this.getStream(t),o=lo.createSubscribeRequest(e,r);let s;try{s=await Kn([o.encode()],Ln,n,Fn,(async e=>await An(e)))}catch(e){return ho.error("Failed to send subscribe request",e),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:t.id}}}const{statusCode:i,requestId:a,statusDesc:c}=uo.decode(s[0].slice());return i<200||i>=300?(ho.error(`Filter subscribe request ${a} failed with status code ${i}: ${c}`),{failure:{error:zr.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async unsubscribe(e,t,r){let n;try{n=await this.getStream(t)}catch(e){return ho.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:zr.NO_STREAM_AVAILABLE,peerId:t.id}}}const o=lo.createUnsubscribeRequest(e,r);try{await Kn([o.encode()],Ln,n.sink)}catch(e){return ho.error("Failed to send unsubscribe request",e),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=lo.createUnsubscribeAllRequest(e),o=await Kn([n.encode()],Ln,r,Fn,(async e=>await An(e)));if(!o||!o.length)return{failure:{error:zr.NO_RESPONSE,peerId:t.id},success:null};const{statusCode:s,requestId:i,statusDesc:a}=uo.decode(o[0].slice());return s<200||s>=300?(ho.error(`Filter unsubscribe all request ${i} failed with status code ${s}: ${a}`),{failure:{error:zr.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async ping(e){let t;try{t=await this.getStream(e)}catch(t){return ho.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:zr.NO_STREAM_AVAILABLE,peerId:e.id}}}const r=lo.createSubscriberPingRequest();let n;try{n=await Kn([r.encode()],Ln,t,Fn,(async e=>await An(e)))}catch(t){return ho.error("Failed to send ping request",t),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:zr.NO_RESPONSE,peerId:e.id}};const{statusCode:o,requestId:s,statusDesc:i}=uo.decode(n[0].slice());return o<200||o>=300?(ho.error(`Filter ping request ${s} failed with status code ${o}: ${i}`),{success:null,failure:{error:zr.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;ho.info(`Received message from ${n.toString()}`);try{Kn(r,Fn,(async e=>{for await(const r of e){const e=co.decode(r.slice()),{pubsubTopic:n,wakuMessage:o}=e;if(!o)return void ho.error("Received empty message");if(!n)return void ho.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,o,t.remotePeer.toString())}})).then((()=>{ho.info("Receiving pipe closed.")}),(async e=>{ho.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){ho.error("Error decoding message",e)}}}class mo{proto;constructor(e){this.proto=e}static createRequest(e,t){return new mo({requestId:ao(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=or.decode(e);return new mo(t)}encode(){return or.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const yo=new gn("light-push"),bo="/vac/waku/lightpush/2.0.0-beta1";class wo extends to{pubsubTopics;constructor(e,t){super(bo,t.components,e),this.pubsubTopics=e}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return yo.error("Failed to send waku light push: payload is empty"),{query:null,error:zr.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return yo.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:zr.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:mo.createRequest(r,e.pubsubTopic),error:null}:(yo.error("Failed to encode to protoMessage, aborting push"),{query:null,error:zr.ENCODE_FAILED})}catch(e){return yo.error("Failed to prepare push message",e),{query:null,error:zr.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:o}=await this.preparePushMessage(e,t);if(o||!n)return{success:null,failure:{error:o,peerId:r.id}};let s,i;try{s=await this.getStream(r)}catch(e){return yo.error("Failed to get stream",e),{success:null,failure:{error:zr.NO_STREAM_AVAILABLE,peerId:r.id}}}try{i=await Kn([n.encode()],Ln,s,Fn,(async e=>await An(e)))}catch(e){return yo.error("Failed to send waku light push request",e),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:r.id}}}const a=new _n;let c;i.forEach((e=>{a.append(e)}));try{c=mo.decode(a).response}catch(e){return yo.error("Failed to decode push reply",e),{success:null,failure:{error:zr.DECODE_FAILED,peerId:r.id}}}if(!c)return yo.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:zr.NO_RESPONSE,peerId:r.id}};if((l=c.info)&&l.includes("could not generate rln-v2 proof")){const e=(e=>{const t={[zr.RLN_IDENTITY_MISSING]:zr.RLN_IDENTITY_MISSING,[zr.RLN_MEMBERSHIP_INDEX]:zr.RLN_MEMBERSHIP_INDEX,[zr.RLN_LIMIT_MISSING]:zr.RLN_LIMIT_MISSING},r=e.toLowerCase();for(const e in t)if(r.includes(e.toLowerCase()))return t[e];return zr.RLN_PROOF_GENERATION})(c.info);return yo.error("Remote peer rejected the message: ",e),{success:null,failure:{error:e,peerId:r.id}}}var l;return c.isSuccess?{success:r.id,failure:null}:(yo.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:zr.REMOTE_PEER_REJECTED,peerId:r.id}})}}const vo={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Eo=1e6;class So{proto;constructor(e){this.proto=e}static create(e){const t=new So({...e,requestId:ao(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Eo):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Eo):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0});if(e.pubsubTopic&&!e.contentTopics||!e.pubsubTopic&&e.contentTopics)throw new Error("Both pubsubTopic and contentTopics must be set or unset");if(e.messageHashes&&(e.pubsubTopic||e.contentTopics||e.timeStart||e.timeEnd))throw new Error("Message hash lookup queries cannot include content filter criteria");return t}static decode(e){const t=cr.decode(e);return new So(t)}encode(){return cr.encode(this.proto)}}class Ao{proto;constructor(e){this.proto=e}static decode(e){const t=lr.decode(e);return new Ao(t)}encode(){return lr.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const ko=new gn("store"),Co="/vac/waku/store-query/3.0.0";class Io extends to{pubsubTopics;constructor(e,t){super(Co,t.components,e),this.pubsubTopics=e}async*queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const o=So.create({...e,paginationCursor:n});let s;try{s=await this.getStream(r)}catch(e){ko.error("Failed to get stream",e);break}const i=await Kn([o.encode()],Ln,s,Fn,(async e=>await An(e))),a=new _n;i.forEach((e=>{a.append(e)}));const c=Ao.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw ko.error(e),new Error(e)}if(!c.messages||!c.messages.length){ko.warn("Stopping pagination due to empty messages in response");break}ko.info(`${c.messages.length} messages retrieved from store`);const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const o=t.get(r);if(o)return o.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...vo,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}class xo extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const 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){const t=super.dispatchEvent(e);let 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 CustomEvent(e,t))}}const To=new gn("keep-alive");class _o{relay;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,libp2p:r}){this.options=e,this.relay=t,this.libp2p=r}start(e){this.stop(e);const{pingKeepAlive:t,relayKeepAlive:r}=this.options,n=e.toString();if(0!==t){const r=setInterval((()=>{(async()=>{let r;try{try{r=await this.libp2p.services.ping.ping(e),To.info(`Ping succeeded (${n})`,r)}catch(e){return void To.error(`Ping failed for peer (${n}).\n Next ping will be attempted in ${t} seconds.\n `)}try{await this.libp2p.peerStore.merge(e,{metadata:{ping:rn(r.toString())}})}catch(e){To.error("Failed to update ping",e)}}catch(e){To.error(`Ping failed (${n})`,e)}})()}),1e3*t);this.pingKeepAliveTimers.set(n,r)}const o=this.relay;if(o&&0!==r){const t=this.scheduleRelayPings(o,r,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){const 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(const 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){const n=[];for(const o of e.pubsubTopics){if(!e.getMeshPeers(o).includes(r))continue;const s=vn({pubsubTopicShardInfo:sn(o),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),i=setInterval((()=>{To.info("Sending Waku Relay ping message"),e.send(s,{payload:new Uint8Array([1])}).catch((e=>To.error("Failed to send relay ping",e)))}),1e3*t);n.push(i)}return n}}const No=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(tn(t)):-1}catch(e){return-1}},Po=new gn("connection-manager");class Lo extends xo{pubsubTopics;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];isP2PNetworkConnected=!1;isConnected(){return!(globalThis?.navigator&&!globalThis?.navigator?.onLine)&&this.isP2PNetworkConnected}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"]),this.stopNetworkStatusListener()}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),Po.info(`Dropped connection with peer ${e.toString()}`)}catch(t){Po.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],o=[],s=[],i=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(Kr.BOOTSTRAP)?r.push(t):e.includes(Kr.PEER_EXCHANGE)?n.push(t):e.includes(Kr.LOCAL)&&o.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(Kr.BOOTSTRAP)?s.push(t):r.includes(Kr.PEER_EXCHANGE)?i.push(t):r.includes(Kr.LOCAL)&&a.push(t)}return{DISCOVERED:{[Kr.BOOTSTRAP]:r,[Kr.PEER_EXCHANGE]:n,[Kr.LOCAL]:o},CONNECTED:{[Kr.BOOTSTRAP]:s,[Kr.PEER_EXCHANGE]:i,[Kr.LOCAL]:a}}}constructor(e){super(),this.libp2p=e.libp2p,this.pubsubTopics=e.pubsubTopics,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,pingKeepAlive:300,relayKeepAlive:300,...e.config},this.keepAliveManager=new _o({relay:e.relay,libp2p:e.libp2p,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.startEventListeners().then((()=>Po.info("Connection Manager is now running"))).catch((e=>Po.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>Po.error("Unexpected error while dialing peer store peers",e)))}async getConnectedPeers(e){const t=this.libp2p.getPeers();return 0===t.length?[]:(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>No(e)-No(t)))}async dialPeerStorePeers(){const e=await this.libp2p.peerStore.all(),t=[];for(const 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){Po.error("Unexpected error while dialing peer store peers",e)}}async startEventListeners(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener(),this.startNetworkStatusListener()}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t<this.options.maxDialAttemptsForPeer;)try{Po.info(`Dialing peer ${e.toString()} on attempt ${t+1}`),await this.libp2p.dial(e);const r=await this.getTagNamesForPeer(e);this.libp2p.getConnections(e).forEach((e=>{e.tags=Array.from(new Set([...e.tags,...r]))})),this.dialAttemptsForPeer.set(e.toString(),-1),this.keepAliveManager.start(e);break}catch(r){r instanceof AggregateError?Po.error(`Error dialing peer ${e.toString()} - ${r.errors}`):Po.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{const t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?Po.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):Po.warn("No errors array found for AggregateError"):r=t.message,Po.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e),await this.attemptDnsDiscovery()}catch(t){throw new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async attemptDnsDiscovery(){if(this.libp2p.getConnections().length>0)return;if((await this.libp2p.peerStore.all()).length>0)return;Po.info("Attempting to trigger DNS discovery.");const e=Object.values(this.libp2p.components.components).find((e=>!(!e||!e.toString)&&e.toString().includes(Jr)));e&&await e.findPeers()}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount<this.options.maxParallelDials){const e=this.pendingPeerDialQueue.shift();if(!e)return;this.attemptDial(e).catch((e=>{Po.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){await this.shouldDialPeer(e)&&(this.currentActiveParallelDialCount>=this.options.maxParallelDials?this.pendingPeerDialQueue.push(e):await this.dialPeer(e))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){Po.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{Po.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t),(await this.getTagNamesForPeer(t)).includes(Kr.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(Kr.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new CustomEvent(Gr.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new CustomEvent(Gr.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.setP2PNetworkConnected()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.setP2PNetworkDisconnected()})()},"browser:network":()=>{this.dispatchWakuConnectionEvent()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return Po.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return Po.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.pubsubTopics}).\n Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(Po.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(Po.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===Kr.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===Kr.BOOTSTRAP)))).length<this.options.maxBootstrapPeersAllowed}async dispatchDiscoveryEvent(e){const t=(await this.getTagNamesForPeer(e)).includes(Kr.BOOTSTRAP);this.dispatchEvent(new CustomEvent(t?Gr.PEER_DISCOVERY_BOOTSTRAP:Gr.PEER_DISCOVERY_PEER_EXCHANGE,{detail:e}))}async getTagNamesForPeer(e){try{const t=await this.libp2p.peerStore.get(e);return Array.from(t.tags.keys())}catch(t){return Po.error(`Failed to get peer ${e}, error: ${t}`),[]}}async isPeerTopicConfigured(e){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return!t||on(t).some((e=>this.pubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return hn(r)}startNetworkStatusListener(){try{globalThis.addEventListener("online",this.onEventHandlers["browser:network"]),globalThis.addEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Po.error(`Failed to start network listener: ${e}`)}}stopNetworkStatusListener(){try{globalThis.removeEventListener("online",this.onEventHandlers["browser:network"]),globalThis.removeEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Po.error(`Failed to stop network listener: ${e}`)}}setP2PNetworkConnected(){this.isP2PNetworkConnected||(this.isP2PNetworkConnected=!0,this.dispatchWakuConnectionEvent())}setP2PNetworkDisconnected(){this.isP2PNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isP2PNetworkConnected=!1,this.dispatchWakuConnectionEvent())}dispatchWakuConnectionEvent(){this.dispatchEvent(new CustomEvent(Wr.CONNECTION_STATUS,{detail:this.isConnected()}))}}class Bo{static instance;health;constructor(){this.health={overallStatus:Yr.Unhealthy,protocolStatuses:new Map}}static getInstance(){return Bo.instance||(Bo.instance=new Bo),Bo.instance}getHealthStatus(){return this.health.overallStatus}getProtocolStatus(e){return this.health.protocolStatuses.get(e)}updateProtocolHealth(e,t){const r=this.getNameFromMulticodec(e);let n=Yr.Unhealthy;1==t?n=Yr.MinimallyHealthy:t>=2&&(n=Yr.SufficientlyHealthy),this.health.protocolStatuses.set(r,{name:r,status:n,lastUpdate:new Date}),this.updateOverallHealth()}getNameFromMulticodec(e){let t;if(e.includes("filter"))t=Vr.Filter;else if(e.includes("lightpush"))t=Vr.LightPush;else{if(!e.includes("store"))throw new Error(`Unknown protocol: ${e}`);t=Vr.Store}return t}updateOverallHealth(){const e=[Vr.LightPush,Vr.Filter].map((e=>this.getProtocolStatus(e)?.status));e.some((e=>e===Yr.Unhealthy))?this.health.overallStatus=Yr.Unhealthy:e.some((e=>e===Yr.MinimallyHealthy))?this.health.overallStatus=Yr.MinimallyHealthy:this.health.overallStatus=Yr.SufficientlyHealthy}}const Oo=()=>Bo.getInstance(),Ro=new gn("metadata"),Do="/vac/waku/metadata/1.0.0";class Uo extends to{pubsubTopics;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(Do,t.components,e),this.pubsubTopics=e,this.libp2pComponents=t,t.registrar.handle(Do,(e=>{this.onRequest(e)}))}async query(e){const t=mr.encode(an(this.pubsubTopics)),r=await this.libp2pComponents.peerStore.get(e);if(!r)return{shardInfo:null,error:zr.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(s){return Ro.error("Failed to get stream",s),{shardInfo:null,error:zr.NO_STREAM_AVAILABLE}}const o=await Kn([t],Ln,n,Fn,(async e=>await An(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(o);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=yr.encode(an(this.pubsubTopics)),o=await Kn([n],Ln,t,Fn,(async e=>await An(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(o);if(s)return;await this.savePeerShardInfo(r.remotePeer,i)}catch(e){Ro.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new _n;e.forEach((e=>{t.append(e)}));const r=yr.decode(t);return r?{shardInfo:r,error:null}:(Ro.error("Error decoding metadata response"),{shardInfo:null,error:zr.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:dn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Mo(e){return t=>new Uo(e,t)}const Fo=Symbol.for("@libp2p/peer-id");function $o(e){return Boolean(e?.[Fo])}const qo=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{const 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 o=0,s=0;const i=this.peekChar();if(void 0===i)return;const a="0"===i,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(o*=e,o+=r,o>c)return;if(s+=1,void 0!==t&&s>t)return}return 0===s||!r&&a&&s>1?void 0:o}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.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]}const 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((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const o=new Uint8Array(14),s=16-(r+2),[i]=e(o.subarray(0,s));return t.set(o.subarray(0,i),16-i),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Ho(e){if(!(e.length>15))return qo.new(e).parseWith((()=>qo.readIPv4Addr()))}function jo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return qo.new(e).parseWith((()=>qo.readIPv6Addr()))}function Vo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return qo.new(e).parseWith((()=>qo.readIPAddr()))}const zo=(parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]));function Ko(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const r of e)if(!(t<0)){if(t>11)break;if(255!==r)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let r=0;for(const n of e)if(!(r<0)){if(r>11)break;if(n!==t[r])return!1;r++}return!0}(e,zo)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw new Error("Failed to mask ip");const n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e[o]&t[o];return n}function Go(e,t){if(32!==t&&128!==t)throw new Error("Invalid CIDR mask");if(e<0||e>t)throw new Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class Wo{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw new Error("Failed to parse given CIDR: "+e);let n=4,o=Ho(t);if(null==o&&(n=16,o=jo(t),null==o))throw new Error("Failed to parse given CIDR: "+e);const s=parseInt(r,10);if(Number.isNaN(s)||String(s).length!==r.length||s<0||s>8*n)throw new Error("Failed to parse given CIDR: "+e);const i=Go(s,8*n);return{network:Ko(o,i),mask:i}}(e));else{const r=Vo(e);if(null==r)throw new Error("Failed to parse network");t=String(t);const n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>8*r.length){const e=Vo(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=Go(n,8*r.length);this.network=Ko(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Vo(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!=(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?String(e):function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}(this.network)+"/"+t}}function Jo(e){return Boolean(Ho(e))}function Xo(e){return Boolean(jo(e))}function Yo(e){return Boolean(Vo(e))}const Zo=Jo,Qo=Xo,es=function(e){let t=0;if(e=e.toString().trim(),Zo(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach((e=>{r[t++]=255&parseInt(e,10)})),r}if(Qo(e)){const r=e.split(":",8);let n;for(n=0;n<r.length;n++){let e;Zo(r[n])&&(e=es(r[n]),r[n]=Zr(e.slice(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,Zr(e.slice(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const o=new Uint8Array(t+16);for(n=0;n<r.length;n++){const e=parseInt(r[n],16);o[t++]=e>>8&255,o[t++]=255&e}return o}throw new Error("invalid ip address")},ts=-1,rs={},ns={};function os(e){if("number"==typeof e){if(null!=ns[e])return ns[e];throw new Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=rs[e])return rs[e];throw new Error(`no protocol with name: ${e}`)}throw new Error("invalid protocol id type: "+typeof e)}function ss(e,t){switch(os(e).code){case 4:case 41:return function(e){const t=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(4===r){const n=[];for(let o=0;o<r;o++)n.push(e[t+o]);return n.join(".")}if(16===r){const e=[];for(let o=0;o<r;o+=2)e.push(n.getUint16(t+o).toString(16));return e.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""}(e,0,e.length);if(null==t)throw new Error("ipBuff is required");if(!Yo(t))throw new Error("invalid ip address");return t}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ds(t);case 43:return Zr(t,"base10");case 6:case 273:case 33:case 132:return us(t).toString();case 421:return function(e){const t=N(e),r=e.slice(I(t));if(r.length!==t)throw new Error("inconsistent lengths");return Zr(r,"base58btc")}(t);case 444:case 445:return function(e){const t=e.slice(0,e.length-2),r=e.slice(e.length-2);return`${Zr(t,"base32")}:${us(r)}`}(t);case 466:return function(e){const t=N(e),r=e.slice(I(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+Zr(r,"base64url")}(t);case 481:return globalThis.encodeURIComponent(ds(t));default:return Zr(t,"base16")}}function is(e,t){switch(os(e).code){case 4:case 41:return function(e){if(!Yo(e))throw new Error("invalid ip address");return es(e)}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hs(t);case 43:return xt(t,"base10");case 6:case 273:case 33:case 132:return ls(parseInt(t,10));case 421:return function(e){let t;t="Q"===e[0]||"1"===e[0]?st(Se.decode(`z${e}`)).bytes:yt.parse(e).multihash.bytes;const r=Uint8Array.from(_(t.length));return kn([r,t],r.length+t.length)}(t);case 444:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=he.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const o=ls(n);return kn([r,o],r.length+o.length)}(t);case 445:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=he.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const o=ls(n);return kn([r,o],r.length+o.length)}(t);case 466:return function(e){const t=cs.decode(e),r=Uint8Array.from(_(t.length));return kn([r,t],r.length+t.length)}(t);case 481:return hs(globalThis.decodeURIComponent(t));default:return xt(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,ts,"ip6zone"],[43,8,"ipcidr"],[53,ts,"dns",!0],[54,ts,"dns4",!0],[55,ts,"dns6",!0],[56,ts,"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,ts,"unix",!1,!0],[421,ts,"ipfs"],[421,ts,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,ts,"garlic64"],[448,0,"tls"],[449,ts,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,ts,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,ts,"http-path"],[777,ts,"memory"]].forEach((e=>{const t=function(e,t,r,n,o){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(o)}}(...e);ns[t.code]=t,rs[t.name]=t})),os("ip4"),os("ip6"),os("ipcidr");const as=Object.values(St).map((e=>e.decoder)),cs=function(){let e=as[0].or(as[1]);return as.slice(2).forEach((t=>e=e.or(t))),e}();function ls(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function us(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function hs(e){const t=xt(e),r=Uint8Array.from(_(t.length));return kn([r,t],r.length+t.length)}function ds(e){const t=N(e);if((e=e.slice(I(t))).length!==t)throw new Error("inconsistent lengths");return Zr(e)}function ps(e){const t=[],r=[];let n=null,o=0;for(;o<e.length;){const s=N(e,o),i=I(s),a=os(s),c=ms(a,e.slice(o+i));if(0===c){t.push([s]),r.push([s]),o+=i;continue}const l=e.slice(o+i,o+i+c);if(o+=c+i,o>e.length)throw bs("Invalid address Uint8Array: "+Zr(e,"base16"));t.push([s,l]);const u=ss(s,l);if(r.push([s,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:fs(r),tuples:t,stringTuples:r,path:n}}function fs(e){const t=[];return e.map((e=>{const r=os(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),ys(t.join("/"))}function gs(e){return kn(e.map((e=>{const t=os(e[0]);let r=Uint8Array.from(_(t.code));return e.length>1&&null!=e[1]&&(r=kn([r,e[1]])),r})))}function ms(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=N(t instanceof Uint8Array?t:Uint8Array.from(t));return e+I(e)}}function ys(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function bs(e){return new Error("Error parsing address: "+e)}const ws=Symbol.for("nodejs.util.inspect.custom"),vs=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Es=[os("dns").code,os("dns4").code,os("dns6").code,os("dnsaddr").code];class Ss extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class As{bytes;#t;#r;#n;#o;[vs]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=ps(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw new Error(`multiaddr "${e}" must start with a "/"`);t=function(e){const t=[],r=[];let n=null;const o=(e=ys(e)).split("/").slice(1);if(1===o.length&&""===o[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){const i=os(o[s]);if(0===i.size){t.push([i.code]),r.push([i.code]);continue}if(s++,s>=o.length)throw bs("invalid address: "+e);if(!0===i.path){n=ys(o.slice(s).join("/")),t.push([i.code,is(i.code,n)]),r.push([i.code,n]);break}const a=is(i.code,o[s]);t.push([i.code,a]),r.push([i.code,ss(i.code,a)])}return{string:fs(r),bytes:gs(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!Cs(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=ps(e.bytes)}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#o=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,o="";const s=os("tcp"),i=os("udp"),a=os("ip4"),c=os("ip6"),l=os("dns6"),u=os("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(o=`%${d??""}`),Es.includes(h)&&(t=s.name,n=443,r=`${d??""}${o}`,e=h===l.code?6:4),h!==s.code&&h!==i.code||(t=os(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=os(h).name,r=`${d??""}${o}`,e=h===c.code?6:4);if(null==e||null==t||null==r||null==n)throw new 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({},os(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>os(e).name))}tuples(){return this.#r.map((([e,t])=>null==t?[e]:[e,t]))}stringTuples(){return this.#n.map((([e,t])=>null==t?[e]:[e,t]))}encapsulate(e){return e=new As(e),new As(this.toString()+e.toString())}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new As(r.slice(0,n))}decapsulateCode(e){const t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new As(gs(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===rs.p2p.code&&e.push([t,r]),t===rs["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?Zr(Se.decode(`z${e}`),"base58btc"):Zr(yt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#o}equals(e){return Cn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=ks.get(t.name);if(null==r)throw new Ss(`no available resolver for ${t.name}`);return(await r(this,e)).map((e=>Is(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){const t=(e??this).protos();return!(2!==t.length||4!==t[0].code&&41!==t[0].code||6!==t[1].code&&273!==t[1].code)}[ws](){return`Multiaddr(${this.#t})`}}const ks=new Map;function Cs(e){return Boolean(e?.[vs])}function Is(e){return new As(e)}function xs(e,t){const r=rn(e),n=rn(t.contentTopic),o=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),function(e){const 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)}(t)}(t.timestamp),s=nn([r,t.payload,n,t.meta,o].filter(Ar));return jr(s)}class Ts{peers=[];isStarted=!1;pubsubTopic;config;libp2p;filter;peerManager;connectionManager;activeSubscriptions;keepAliveIntervalId;pingFailedAttempts=new Map;receivedMessagesFormPeer=new Set;receivedMessages=new Set;verifiedPeers=new Set;constructor(e){this.config=e.config,this.connectionManager=e.connectionManager,this.filter=e.filter,this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.activeSubscriptions=e.activeSubscriptions,this.pubsubTopic=e.pubsubTopic,this.onConnectionChange=this.onConnectionChange.bind(this),this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}get reservedContentTopic(){return`/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`}start(){this.isStarted||(this.isStarted=!0,this.startKeepAlive(),this.startConnectionListener(),this.startPeerConnectionListener())}stop(){this.isStarted&&(this.isStarted=!1,this.stopKeepAlive(),this.stopConnectionListener(),this.stopPeerConnectionListener())}async getPeers(){return this.isStarted||(this.peers=await this.peerManager.getPeers()),this.peers}notifyMessageReceived(e,t){const r=this.buildMessageHash(t);return this.verifiedPeers.add(e),this.receivedMessagesFormPeer.add(`${e}-${r}`),!!this.receivedMessages.has(r)||(this.receivedMessages.add(r),!1)}buildMessageHash(e){return function(e,t){const r=xs(e,t);return en(r)}(this.pubsubTopic,e)}startConnectionListener(){this.connectionManager.addEventListener(Wr.CONNECTION_STATUS,this.onConnectionChange)}stopConnectionListener(){this.connectionManager.removeEventListener(Wr.CONNECTION_STATUS,this.onConnectionChange)}async onConnectionChange({detail:e}){e?(await Promise.all(this.peers.map((e=>this.ping(e,!0)))),this.startKeepAlive()):this.stopKeepAlive()}startKeepAlive(){this.keepAliveIntervalId||(this.keepAliveIntervalId=setInterval((()=>{this.peers.map((e=>this.ping(e)))}),this.config.keepAliveIntervalMs))}stopKeepAlive(){this.keepAliveIntervalId&&(clearInterval(this.keepAliveIntervalId),this.keepAliveIntervalId=void 0)}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onPeerConnected),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected)}stopPeerConnectionListener(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnected),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected)}async onPeerConnected(e){this.peers.length>0||(this.peers=await this.peerManager.getPeers(),await Promise.all(this.peers.map((e=>this.subscribe(e)))))}async onPeerDisconnected(e){!this.peers.find((t=>t.id.equals(e.detail)))||(this.peers=await this.peerManager.getPeers(),await Promise.all(this.peers.map((e=>this.subscribe(e)))))}async subscribe(e){let t=e;for(let e=0;e<3;e++){if(!t)return;if((await this.filter.subscribe(this.pubsubTopic,t,Array.from(this.activeSubscriptions.keys()))).success)return;t=await this.peerManager.requestRenew(t.id)}}async ping(e,t=!1){const r=e.id.toString(),n=await this.filter.ping(e);if(n.failure&&t){const t=await this.peerManager.requestRenew(e.id);await this.subscribe(t)}else{if(n.failure){const e=this.pingFailedAttempts.get(r)||0;this.pingFailedAttempts.set(r,e+1)}if(n.success&&this.pingFailedAttempts.set(r,0),(this.pingFailedAttempts.get(r)||0)>=this.config.pingsBeforePeerRenewed){const t=await this.peerManager.requestRenew(e.id);await this.subscribe(t)}}}}const _s=new gn("sdk:filter:subscription");class Ns{pubsubTopic;protocol;config;monitor;subscriptionCallbacks=new Map;constructor(e,t,r,n,o,s,i){this.pubsubTopic=e,this.protocol=t,this.config=s,this.pubsubTopic=e,this.monitor=new Ts({pubsubTopic:e,config:s,libp2p:o,connectionManager:r,filter:t,peerManager:n,lightPush:i,activeSubscriptions:this.subscriptionCallbacks})}async subscribe(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:zr.TOPIC_DECODER_MISMATCH}],successes:[]};this.config.enableLightPushFilterCheck&&r.push(Sn(this.monitor.reservedContentTopic,this.pubsubTopic));const n=kr(r),o=Array.from(n.keys()),s=(await this.monitor.getPeers()).map((async e=>this.protocol.subscribe(this.pubsubTopic,e,o))),i=await Promise.allSettled(s),a=this.handleResult(i,"subscribe");return n.forEach(((e,r)=>{const n={decoders:e,callback:t};r!==this.monitor.reservedContentTopic&&this.subscriptionCallbacks.set(r,n)})),this.monitor.start(),a}async unsubscribe(e){const t=(await this.monitor.getPeers()).map((async t=>{const r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach((e=>{this.subscriptionCallbacks.delete(e)})),r})),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.monitor.stop(),n}async ping(){const e=(await this.monitor.getPeers()).map((e=>this.protocol.ping(e))),t=await Promise.allSettled(e);return this.handleResult(t,"ping")}async unsubscribeAll(){const e=(await this.monitor.getPeers()).map((async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e))),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();const r=this.handleResult(t,"unsubscribeAll");return this.monitor.stop(),r}async processIncomingMessage(e,t){if(this.monitor.notifyMessageReceived(t,e))return void _s.info("Message already received, skipping");const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(_s.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await async function(e,t,r){const{decoders:n,callback:o}=e,{contentTopic:s}=r;if(s)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),s=await Promise.any(e);await o(s)}catch(e){_s.error("Error decoding message",e)}else _s.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):_s.error("No subscription callback available for ",r)}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)_s.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:zr.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}}const Ps=new gn("sdk:filter");class Ls{connectionManager;libp2p;peerManager;lightPush;protocol;config;activeSubscriptions=new Map;constructor(e,t,r,n,o){this.connectionManager=e,this.libp2p=t,this.peerManager=r,this.lightPush=n,this.config=(e=>({keepAliveIntervalMs:e?.keepAliveIntervalMs||6e4,pingsBeforePeerRenewed:e?.pingsBeforePeerRenewed||3,enableLightPushFilterCheck:e?.enableLightPushFilterCheck||!1}))(o),this.protocol=new go((async(e,t,r)=>{const n=this.getActiveSubscription(e);n?await n.processIncomingMessage(t,r):Ps.error(`No subscription locally registered for topic ${e}`)}),e.pubsubTopics,t),this.activeSubscriptions=new Map}async subscribe(e,t){const r=this.getUniquePubsubTopics(e);if(1!==r.length)return{subscription:null,error:zr.INVALID_DECODER_TOPICS,results:null};const n=r[0],{subscription:o,error:s}=await this.createSubscription(n);if(s)return{subscription:null,error:s,results:null};const{failures:i,successes:a}=await o.subscribe(e,t);return{subscription:o,error:null,results:{failures:i,successes:a}}}async createSubscription(e){const t="string"==typeof e?e:on(e)?.[0];cn(t,this.protocol.pubsubTopics);const r=await this.peerManager.getPeers();return 0===r.length?{error:zr.NO_PEER_AVAILABLE,subscription:null}:(Ps.info(`Creating filter subscription with ${r.length} peers: `,r.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(t)??this.setActiveSubscription(t,new Ns(t,this.protocol,this.connectionManager,this.peerManager,this.libp2p,this.config,this.lightPush))})}async subscribeWithUnsubscribe(e,t){const r=this.getUniquePubsubTopics(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.");const{subscription:n,error:o}=await this.createSubscription(r[0]);if(o)throw Error(`Failed to create subscription: ${o}`);await n.subscribe(e,t);const s=Array.from(kr(Array.isArray(e)?e:[e]).keys());return async()=>{await n.unsubscribe(s)}}toSubscriptionIterator(e){return async function(e,t,r){const n=[];let o;o=await e.subscribeWithUnsubscribe(t,(e=>{n.push(e)}));const s=Number.isInteger(r?.timeoutMs),i=Date.now();return{iterator:async function*(){for(;;){if(s&&Date.now()-i>=0)return;await Cr(60);const e=n.shift();if(!o&&0===n.length)return e;!e&&o||(yield e)}}(),async stop(){o&&(await o(),o=void 0)}}}(this,e)}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}getUniquePubsubTopics(e){if(!Array.isArray(e))return[e.pubsubTopic];if(0===e.length)return[];const t=new Set(e.map((e=>e.pubsubTopic)));return[...t]}}const Bs=new gn("sdk:light-push"),Os={autoRetry:!1,maxAttempts:3};class Rs{peerManager;protocol;constructor(e,t,r){this.peerManager=t,this.protocol=new wo(e.pubsubTopics,r)}async send(e,t,r=Os){const n=[],o=[],{pubsubTopic:s}=e;try{cn(s,this.protocol.pubsubTopics)}catch(e){return Bs.error("Failed to send waku light push: pubsub topic not configured"),{successes:n,failures:[{error:zr.TOPIC_NOT_CONFIGURED}]}}const i=await this.peerManager.getPeers();if(0===i.length)return{successes:n,failures:[{error:zr.NO_PEER_AVAILABLE}]};const a=await Promise.allSettled(i.map((r=>this.protocol.send(e,t,r))));for(const s of a){if("fulfilled"!==s.status){Bs.error("Failed unexpectedly while sending:",s.reason),o.push({error:zr.GENERIC_FAIL});continue}const{failure:i,success:a}=s.value;a?n.push(a):i&&(o.push(i),r?.autoRetry&&this.attemptRetries((r=>this.protocol.send(e,t,r)),r.maxAttempts))}return Oo().updateProtocolHealth(this.protocol.multicodec,n.length),{successes:n,failures:o}}async attemptRetries(e,t){t=t||3;const r=await this.peerManager.getPeers();if(0!==r.length)for(let n=0;n<t;n++){const t=r[n%r.length],o=await e(t);if(o.success)return;Bs.info(`Attempted retry for peer:${t.id} failed with:${o?.failure?.error}`)}else Bs.warn("Cannot retry with no connected peers.")}}const Ds=new gn("peer-manager"),Us="peer-manager-lock";class Ms{numPeersToUse;libp2p;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||2,this.libp2p=e.libp2p,this.startConnectionListener()}stop(){this.stopConnectionListener()}async getPeers(){return Promise.all(this.getLockedConnections().map((e=>this.mapConnectionToPeer(e))))}async requestRenew(e){const t=this.getLockedConnections(),r=this.numPeersToUse-t.length;if(0===r)return;const n=(await Promise.all(this.getUnlockedConnections().filter((t=>!t.remotePeer.equals(e))).slice(0,r).map((e=>this.lockConnection(e))).map((e=>this.mapConnectionToPeer(e)))))[0];if(n)return Ds.info(`requestRenew: Renewed peer ${e.toString()} to ${n.id.toString()}`),n;Ds.warn(`requestRenew: Couldn't renew peer ${e.toString()}.`)}startConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stopConnectionListener(){this.libp2p.removeEventListener("peer:connect",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}onConnected(e){const t=e.detail;this.lockPeerIfNeeded(t)}onDisconnected(e){const t=e.detail;this.requestRenew(t)}async lockPeerIfNeeded(e){const t=this.getLockedConnections();0!=this.numPeersToUse-t.length&&this.getUnlockedConnections().filter((t=>t.remotePeer.equals(e))).map((e=>this.lockConnection(e)))}getLockedConnections(){return this.libp2p.getConnections().filter((e=>"open"===e.status&&this.isConnectionLocked(e)))}getUnlockedConnections(){return this.libp2p.getConnections().filter((e=>"open"===e.status&&!this.isConnectionLocked(e)))}lockConnection(e){return Ds.info(`requestRenew: Locking connection for peerId=${e.remotePeer.toString()}`),e.tags.push(Us),e}isConnectionLocked(e){return e.tags.includes(Us)}async mapConnectionToPeer(e){const t=e.remotePeer;return this.libp2p.peerStore.get(t)}}const Fs=new gn("waku:store:sdk");class $s{peerManager;protocol;constructor(e,t,r){this.peerManager=r,this.protocol=new Io(e.pubsubTopics,t)}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:o}=this.validateDecodersAndPubsubTopic(e),s={pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t},i=(await this.peerManager.getPeers())[0];if(!i)throw Fs.error("No peers available to query"),new Error("No peers available to query");Fs.info(`Querying store with options: ${JSON.stringify(t)}`);const a=this.protocol.queryPerPage(s,o,i);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){Fs.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){Fs.info("Querying store with promise callback");let n=!1;for await(const o of this.queryGenerator(e,r)){const e=o.map((async e=>{n||(n=Boolean(await t(e)))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(Ar);return await Promise.all(n.map((async e=>{e&&!r&&(r=Boolean(await t(e)))}))),r}createCursor(e){return xs(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw Fs.error("No decoders provided"),new Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw Fs.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const r=t[0];cn(r,this.protocol.pubsubTopics);const n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw Fs.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const o=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===o.length)throw Fs.error(`No decoders found for topic ${r}`),new Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:o,decodersAsMap:n}}}const qs=new gn("wait-for-remote-peer");async function Hs(e,t){qs.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async o=>{if(o.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(o.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&qs.error("Connection closed. Some peers can be on different shard."),qs.error(`Error waiting for metadata: ${e}`)}}};t.addEventListener("peer:identify",n)}))}const js=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),Vs=new gn("waku");class zs{pubsubTopics;libp2p;relay;store;filter;lightPush;connectionManager;health;peerManager;constructor(e,t,r,n,o){this.pubsubTopics=e,this.relay=o,this.libp2p=r,n={filter:!1,lightpush:!1,store:!1,...n};const s=this.libp2p.peerId.toString();if(this.connectionManager=new Lo({libp2p:r,relay:this.relay,pubsubTopics:this.pubsubTopics,config:t?.connectionManager}),this.peerManager=new Ms({libp2p:r,config:{numPeersToUse:t.numPeersToUse}}),this.health=Oo(),n.store){const e=(i=this.connectionManager,a=this.peerManager,e=>new $s(i,e,a));this.store=e(r)}var i,a;if(n.lightpush){const e=function(e,t){return r=>new Rs(e,t,r)}(this.connectionManager,this.peerManager);this.lightPush=e(r)}if(n.filter){const e=function(e,t,r,n){return o=>new Ls(e,o,t,r,n)}(this.connectionManager,this.peerManager,this.lightPush,t.filter);this.filter=e(r)}Vs.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}async dial(e,t){const r=t??[],n=this.mapToPeerIdOrMultiaddr(e);void 0===t&&(this.relay&&r.push(Vr.Relay),this.store&&r.push(Vr.Store),this.filter&&r.push(Vr.Filter),this.lightPush&&r.push(Vr.LightPush));const o=[];return r.includes(Vr.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>o.push(e))):Vs.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Vr.Store)&&(this.store?o.push(this.store.protocol.multicodec):Vs.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Vr.LightPush)&&(this.lightPush?o.push(this.lightPush.protocol.multicodec):Vs.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Vr.Filter)&&(this.filter?o.push(this.filter.protocol.multicodec):Vs.error("Filter codec not included in dial codec: protocol not mounted locally")),Vs.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,o)}async start(){await this.libp2p.start()}async stop(){this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop()}async getPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Vr.Relay),e.filter&&t.push(Vr.Filter),e.store&&t.push(Vr.Store),e.lightPush&&t.push(Vr.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");if(n.length>0&&!t.includes(Vr.Relay)){const r=await async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,o=function(e){const t=new Map,r={[Vr.Filter]:po,[Vr.LightPush]:bo,[Vr.Store]:Co};for(const n of e)r[n]&&t.set(r[n],!1);return t}(t);if(!r.length||!n)return qs.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`),!1;for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>o.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{o.has(e)&&o.set(e,!0)})),Array.from(o.values()).every((e=>e))))return!0}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&qs.error("Connection closed. Some peers can be on different shard."),qs.error(`Error while iterating through peers: ${e}`);continue}return!1}(e,t);if(r)return}const o=[];if(t.includes(Vr.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");o.push(e.relay.waitForPeers())}if(t.includes(Vr.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");o.push(Hs(Co,e.libp2p))}if(t.includes(Vr.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");o.push(Hs(bo,e.libp2p))}if(t.includes(Vr.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");o.push(Hs(po,e.libp2p))}r?await async function(e,t){await Promise.race([e,js(t,"Timed out waiting for a remote peer.")])}(Promise.all(o),r):await Promise.all(o)}(this,e,t)}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}mapToPeerIdOrMultiaddr(e){return $o(e)?e:Is(e)}}class Ks extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Gs extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}Error;class Ws extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Js extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Xs extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}Error;class Ys extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class Zs extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Qs extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class ei extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class ti extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class ri extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class ni extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}}class oi extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}class si extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}}class ii extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class ai extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class ci extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class li extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class ui extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}class hi extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}}class di extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}Error;class pi extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}Error;class fi extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class gi extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class mi extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class yi extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const bi=BigInt(2**32-1),wi=BigInt(32);function vi(e,t=!1){return t?{h:Number(e&bi),l:Number(e>>wi&bi)}:{h:0|Number(e>>wi&bi),l:0|Number(e&bi)}}const Ei={fromBig:vi,split:function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;o<e.length;o++){const{h:s,l:i}=vi(e[o],t);[r[o],n[o]]=[s,i]}return[r,n]},toBig:(e,t)=>BigInt(e>>>0)<<wi|BigInt(t>>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,r)=>e<<r|t>>>32-r,rotlSL:(e,t,r)=>t<<r|e>>>32-r,rotlBH:(e,t,r)=>t<<r-32|e>>>64-r,rotlBL:(e,t,r)=>e<<r-32|t>>>64-r,add:function(e,t,r,n){const o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:0|o}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,add5H:(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,add5L:(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0)},Si=Ei,[Ai,ki]=(()=>Si.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),Ci=new Uint32Array(80),Ii=new Uint32Array(80);class xi extends Mr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:s,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,o,s,i,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,o,s,i,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|o,this.Cl=0|s,this.Dh=0|i,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)Ci[r]=e.getUint32(t),Ii[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Ci[e-15],r=0|Ii[e-15],n=Si.rotrSH(t,r,1)^Si.rotrSH(t,r,8)^Si.shrSH(t,r,7),o=Si.rotrSL(t,r,1)^Si.rotrSL(t,r,8)^Si.shrSL(t,r,7),s=0|Ci[e-2],i=0|Ii[e-2],a=Si.rotrSH(s,i,19)^Si.rotrBH(s,i,61)^Si.shrSH(s,i,6),c=Si.rotrSL(s,i,19)^Si.rotrBL(s,i,61)^Si.shrSL(s,i,6),l=Si.add4L(o,c,Ii[e-7],Ii[e-16]),u=Si.add4H(l,n,a,Ci[e-7],Ci[e-16]);Ci[e]=0|u,Ii[e]=0|l}let{Ah:r,Al:n,Bh:o,Bl:s,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Si.rotrSH(u,h,14)^Si.rotrSH(u,h,18)^Si.rotrBH(u,h,41),b=Si.rotrSL(u,h,14)^Si.rotrSL(u,h,18)^Si.rotrBL(u,h,41),w=u&d^~u&f,v=h&p^~h&g,E=Si.add5L(y,b,v,ki[e],Ii[e]),S=Si.add5H(E,m,t,w,Ai[e],Ci[e]),A=0|E,k=Si.rotrSH(r,n,28)^Si.rotrBH(r,n,34)^Si.rotrBH(r,n,39),C=Si.rotrSL(r,n,28)^Si.rotrBL(r,n,34)^Si.rotrBL(r,n,39),I=r&o^r&i^o&i,x=n&s^n&a^s&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=Si.add(0|c,0|l,0|S,0|A)),c=0|i,l=0|a,i=0|o,a=0|s,o=0|r,s=0|n;const T=Si.add3L(A,C,x);r=Si.add3H(T,S,k,I),n=0|T}({h:r,l:n}=Si.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:o,l:s}=Si.add(0|this.Bh,0|this.Bl,0|o,0|s)),({h:i,l:a}=Si.add(0|this.Ch,0|this.Cl,0|i,0|a)),({h:c,l}=Si.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=Si.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=Si.add(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=Si.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Si.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,o,s,i,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){Ci.fill(0),Ii.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ti=Rr((()=>new xi)),_i=BigInt(0),Ni=BigInt(1),Pi=BigInt(2);function Li(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Bi(e){if(!Li(e))throw new Error("Uint8Array expected")}function Oi(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const Ri=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Di(e){Bi(e);let t="";for(let r=0;r<e.length;r++)t+=Ri[e[r]];return t}function Ui(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Mi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_i:BigInt("0x"+e)}const Fi={_0:48,_9:57,A:65,F:70,a:97,f:102};function $i(e){return e>=Fi._0&&e<=Fi._9?e-Fi._0:e>=Fi.A&&e<=Fi.F?e-(Fi.A-10):e>=Fi.a&&e<=Fi.f?e-(Fi.a-10):void 0}function qi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,o=0;t<r;t++,o+=2){const r=$i(e.charCodeAt(o)),s=$i(e.charCodeAt(o+1));if(void 0===r||void 0===s){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}n[t]=16*r+s}return n}function Hi(e){return Mi(Di(e))}function ji(e){return Bi(e),Mi(Di(Uint8Array.from(e).reverse()))}function Vi(e,t){return qi(e.toString(16).padStart(2*t,"0"))}function zi(e,t){return Vi(e,t).reverse()}function Ki(e,t,r){let n;if("string"==typeof t)try{n=qi(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Li(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const o=n.length;if("number"==typeof r&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function Gi(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Bi(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const o=e[t];r.set(o,n),n+=o.length}return r}const Wi=e=>"bigint"==typeof e&&_i<=e;function Ji(e,t,r){return Wi(e)&&Wi(t)&&Wi(r)&&t<=e&&e<r}function Xi(e,t,r,n){if(!Ji(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Yi(e){let t;for(t=0;e>_i;e>>=Ni,t+=1);return t}const Zi=e=>(Pi<<BigInt(e-1))-Ni,Qi=e=>new Uint8Array(e),ea=e=>Uint8Array.from(e);function ta(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let n=Qi(e),o=Qi(e),s=0;const i=()=>{n.fill(1),o.fill(0),s=0},a=(...e)=>r(o,n,...e),c=(e=Qi())=>{o=a(ea([0]),e),n=a(),0!==e.length&&(o=a(ea([1]),e),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){n=a();const t=n.slice();r.push(t),e+=n.length}return Gi(...r)};return(e,t)=>{let r;for(i(),c(e);!(r=t(l()));)c();return i(),r}}const ra={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Li(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function na(e,t,r={}){const n=(t,r,n)=>{const o=ra[r];if("function"!=typeof o)throw new Error("invalid validator function");const s=e[t];if(!(n&&void 0===s||o(s,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+s)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function oa(e){const t=new WeakMap;return(r,...n)=>{const o=t.get(r);if(void 0!==o)return o;const s=e(r,...n);return t.set(r,s),s}}const sa=BigInt(0),ia=BigInt(1),aa=BigInt(2),ca=BigInt(3),la=BigInt(4),ua=BigInt(5),ha=BigInt(8);function da(e,t){const r=e%t;return r>=sa?r:t+r}function pa(e,t,r){if(t<sa)throw new Error("invalid exponent, negatives unsupported");if(r<=sa)throw new Error("invalid modulus");if(r===ia)return sa;let n=ia;for(;t>sa;)t&ia&&(n=n*e%r),e=e*e%r,t>>=ia;return n}function fa(e,t,r){let n=e;for(;t-- >sa;)n*=n,n%=r;return n}function ga(e,t){if(e===sa)throw new Error("invert: expected non-zero number");if(t<=sa)throw new Error("invert: expected positive modulus, got "+t);let r=da(e,t),n=t,o=sa,s=ia,i=ia,a=sa;for(;r!==sa;){const e=n/r,t=n%r,c=o-i*e,l=s-a*e;n=r,r=t,o=i,s=a,i=c,a=l}if(n!==ia)throw new Error("invert: does not exist");return da(o,t)}const ma=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ya(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function ba(e,t,r=!1,n={}){if(e<=sa)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:o,nByteLength:s}=ya(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i;const a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:Zi(o),ZERO:sa,ONE:ia,create:t=>da(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return sa<=t&&t<e},is0:e=>e===sa,isOdd:e=>(e&ia)===ia,neg:t=>da(-t,e),eql:(e,t)=>e===t,sqr:t=>da(t*t,e),add:(t,r)=>da(t+r,e),sub:(t,r)=>da(t-r,e),mul:(t,r)=>da(t*r,e),pow:(e,t)=>function(e,t,r){if(r<sa)throw new Error("invalid exponent, negatives unsupported");if(r===sa)return e.ONE;if(r===ia)return t;let n=e.ONE,o=t;for(;r>sa;)r&ia&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ia;return n}(a,e,t),div:(t,r)=>da(t*ga(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ga(t,e),sqrt:n.sqrt||(t=>(i||(i=function(e){if(e%la===ca){const t=(e+ia)/la;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}if(e%ha===ua){const t=(e-ua)/ha;return function(e,r){const n=e.mul(r,aa),o=e.pow(n,t),s=e.mul(r,o),i=e.mul(e.mul(s,aa),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-ia)/aa;let r,n,o;for(r=e-ia,n=0;r%aa===sa;r/=aa,n++);for(o=aa;o<e&&pa(o,t,e)!==e-ia;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===n){const t=(e+ia)/la;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}const s=(r+ia)/aa;return function(e,i){if(e.pow(i,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=n,c=e.pow(e.mul(e.ONE,o),r),l=e.pow(i,s),u=e.pow(i,r);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(u);t<a&&!e.eql(r,e.ONE);t++)r=e.sqr(r);const r=e.pow(c,ia<<BigInt(a-t-1));c=e.sqr(r),l=e.mul(l,r),u=e.mul(u,c),a=t}return l}}(e)}(e)),i(a,t))),invertBatch:e=>function(e,t){const r=new Array(t.length),n=t.reduce(((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n))),e.ONE),o=e.inv(n);return t.reduceRight(((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n))),o),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?zi(e,s):Vi(e,s),fromBytes:e=>{if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);return r?ji(e):Hi(e)}});return Object.freeze(a)}function wa(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function va(e){const t=wa(e);return t+Math.ceil(t/2)}const Ea=BigInt(0),Sa=BigInt(1);function Aa(e,t){const r=t.negate();return e?r:t}function ka(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ca(e,t){return ka(e,t),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Ia=new WeakMap,xa=new WeakMap;function Ta(e){return xa.get(e)||1}function _a(e,t){return{constTimeNegate:Aa,hasPrecomputes:e=>1!==Ta(e),unsafeLadder(t,r,n=e.ZERO){let o=t;for(;r>Ea;)r&Sa&&(n=n.add(o)),o=o.double(),r>>=Sa;return n},precomputeWindow(e,r){const{windows:n,windowSize:o}=Ca(r,t),s=[];let i=e,a=i;for(let e=0;e<n;e++){a=i,s.push(a);for(let e=1;e<o;e++)a=a.add(i),s.push(a);i=a.double()}return s},wNAF(r,n,o){const{windows:s,windowSize:i}=Ca(r,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**r-1),u=2**r,h=BigInt(r);for(let e=0;e<s;e++){const t=e*i;let r=Number(o&l);o>>=h,r>i&&(r-=u,o+=Sa);const s=t,d=t+Math.abs(r)-1,p=e%2!=0,f=r<0;0===r?c=c.add(Aa(p,n[s])):a=a.add(Aa(f,n[d]))}return{p:a,f:c}},wNAFUnsafe(r,n,o,s=e.ZERO){const{windows:i,windowSize:a}=Ca(r,t),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let e=0;e<i;e++){const t=e*a;if(o===Ea)break;let r=Number(o&c);if(o>>=u,r>a&&(r-=l,o+=Sa),0===r)continue;let i=n[t+Math.abs(r)-1];r<0&&(i=i.negate()),s=s.add(i)}return s},getPrecomputes(e,t,r){let n=Ia.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&Ia.set(t,r(n))),n},wNAFCached(e,t,r){const n=Ta(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)},wNAFCachedUnsafe(e,t,r,n){const o=Ta(e);return 1===o?this.unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,n)},setWindowSize(e,r){ka(r,t),xa.set(e,r),Ia.delete(e)}}}function Na(e,t,r,n){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)}))}(n,t),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,s=Yi(BigInt(r.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o);let l=o;for(let e=Math.floor((t.BITS-1)/i)*i;e>=0;e-=i){c.fill(o);for(let t=0;t<n.length;t++){const o=n[t],s=Number(o>>BigInt(e)&BigInt(a));c[s]=c[s].add(r[t])}let t=o;for(let e=c.length-1,r=o;e>0;e--)r=r.add(c[e]),t=t.add(r);if(l=l.add(t),0!==e)for(let e=0;e<i;e++)l=l.double()}return l}function Pa(e){return function(e){const t=ma.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});na(e,t)}(e.Fp),na(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ya(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const La=BigInt(0),Ba=BigInt(1),Oa=BigInt(2),Ra=BigInt(8),Da={zip215:!0};const Ua=BigInt(0),Ma=BigInt(1);const Fa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),$a=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),qa=(BigInt(0),BigInt(1)),Ha=BigInt(2),ja=BigInt(3),Va=BigInt(5),za=BigInt(8);function Ka(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Fa,i=e*e%s*e%s,a=fa(i,Ha,s)*i%s,c=fa(a,qa,s)*e%s,l=fa(c,Va,s)*c%s,u=fa(l,t,s)*l%s,h=fa(u,r,s)*u%s,d=fa(h,n,s)*h%s,p=fa(d,o,s)*d%s,f=fa(p,o,s)*d%s,g=fa(f,t,s)*l%s;return{pow_p_5_8:fa(g,Ha,s)*e%s,b2:i}}function Ga(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Wa(e,t){const r=Fa,n=da(t*t*t,r),o=da(n*n*t,r);let s=da(e*n*Ka(e*o).pow_p_5_8,r);const i=da(t*s*s,r),a=s,c=da(s*$a,r),l=i===e,u=i===da(-e,r),h=i===da(-e*$a,r);return l&&(s=a),(u||h)&&(s=c),(da(s,r)&ia)===ia&&(s=da(-s,r)),{isValid:l||u,value:s}}const Ja=(()=>ba(Fa,void 0,!0))(),Xa=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ja,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:za,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ti,randomBytes:Dr,adjustScalarBytes:Ga,uvRatio:Wa}))(),Ya=(()=>function(e){const t=function(e){const t=Pa(e);return na(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Oa<<BigInt(8*a)-Ba,u=r.create,h=ba(t.n,t.nBitLength),d=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:La}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,r)=>{if(Oi("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){Xi("coordinate "+e,t,La,l)}function m(e){if(!(e instanceof w))throw new Error("ExtendedPoint expected")}const y=oa(((e,t)=>{const{ex:n,ey:o,ez:s}=e,i=e.is0();null==t&&(t=i?Ra:r.inv(s));const a=u(n*t),c=u(o*t),l=u(s*t);if(i)return{x:La,y:Ba};if(l!==Ba)throw new Error("invZ was invalid");return{x:a,y:c}})),b=oa((e=>{const{a:r,d:n}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:o,ey:s,ez:i,et:a}=e,c=u(o*o),l=u(s*s),h=u(i*i),d=u(h*h),p=u(c*r);if(u(h*u(p+l))!==u(d+u(n*u(c*l))))throw new Error("bad point: equation left != right (1)");if(u(o*s)!==u(i*a))throw new Error("bad point: equation left != right (2)");return!0}));class w{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,g("x",e),g("y",t),g("z",r),g("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof w)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return g("x",t),g("y",r),new w(t,r,Ba,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(w.fromAffine)}static msm(e,t){return Na(w,h,e,t)}_setWindowSize(e){S.setWindowSize(this,e)}assertValidity(){b(this)}equals(e){m(e);const{ex:t,ey:r,ez:n}=this,{ex:o,ey:s,ez:i}=e,a=u(t*i),c=u(o*n),l=u(r*i),h=u(s*n);return a===c&&l===h}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:o}=this,s=u(r*r),i=u(n*n),a=u(Oa*u(o*o)),c=u(e*s),l=r+n,h=u(u(l*l)-s-i),d=c+i,p=d-a,f=c-i,g=u(h*p),m=u(d*f),y=u(h*f),b=u(p*d);return new w(g,m,b,y)}add(e){m(e);const{a:r,d:n}=t,{ex:o,ey:s,ez:i,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((s-o)*(l+c)),t=u((s+o)*(l-c)),r=u(t-e);if(r===La)return this.double();const n=u(i*Oa*d),p=u(a*Oa*h),f=p+n,g=t+e,m=p-n,y=u(f*r),b=u(g*m),v=u(f*m),E=u(r*g);return new w(y,b,E,v)}const p=u(o*c),f=u(s*l),g=u(a*n*d),y=u(i*h),b=u((o+s)*(c+l)-p-f),v=y-g,E=y+g,S=u(f-r*p),A=u(b*v),k=u(E*S),C=u(b*S),I=u(v*E);return new w(A,k,I,C)}subtract(e){return this.add(e.negate())}wNAF(e){return S.wNAFCached(this,e,w.normalizeZ)}multiply(e){const t=e;Xi("scalar",t,Ba,n);const{p:r,f:o}=this.wNAF(t);return w.normalizeZ([r,o])[0]}multiplyUnsafe(e,t=w.ZERO){const r=e;return Xi("scalar",r,La,n),r===La?E:this.is0()||r===Ba?this:S.wNAFCachedUnsafe(this,r,w.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return S.unsafeLadder(this,n).is0()}toAffine(e){return y(this,e)}clearCofactor(){const{h:e}=t;return e===Ba?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:o,a:s}=t,i=r.BYTES;e=Ki("pointHex",e,i),Oi("zip215",n);const a=e.slice(),c=e[i-1];a[i-1]=-129&c;const h=ji(a),p=n?l:r.ORDER;Xi("pointHex.y",h,La,p);const f=u(h*h),g=u(f-Ba),m=u(o*f-s);let{isValid:y,value:b}=d(g,m);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const v=(b&Ba)===Ba,E=!!(128&c);if(!n&&b===La&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(b=u(-b)),w.fromAffine({x:b,y:h})}static fromPrivateKey(e){return C(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=zi(t,r.BYTES);return n[n.length-1]|=e&Ba?128:0,n}toHex(){return Di(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,Ba,u(t.Gx*t.Gy)),w.ZERO=new w(La,Ba,Ba,La);const{BASE:v,ZERO:E}=w,S=_a(w,8*a);function A(e){return da(e,n)}function k(e){return A(ji(e))}function C(e){const t=r.BYTES;e=Ki("private key",e,t);const n=Ki("hashed private key",s(e),2*t),o=p(n.slice(0,t)),i=n.slice(t,2*t),a=k(o),c=v.multiply(a),l=c.toRawBytes();return{head:o,prefix:i,scalar:a,point:c,pointBytes:l}}function I(e=new Uint8Array,...t){const r=Gi(...t);return k(s(f(r,Ki("context",e),!!o)))}const x=Da;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return C(e).pointBytes},sign:function(e,t,s={}){e=Ki("message",e),o&&(e=o(e));const{prefix:i,scalar:a,pointBytes:c}=C(t),l=I(s.context,i,e),u=v.multiply(l).toRawBytes(),h=A(l+I(s.context,u,c,e)*a);return Xi("signature.s",h,La,n),Ki("result",Gi(u,zi(h,r.BYTES)),2*r.BYTES)},verify:function(e,t,n,s=x){const{context:i,zip215:a}=s,c=r.BYTES;e=Ki("signature",e,2*c),t=Ki("message",t),n=Ki("publicKey",n,c),void 0!==a&&Oi("zip215",a),o&&(t=o(t));const l=ji(e.slice(c,2*c));let u,h,d;try{u=w.fromHex(n,a),h=w.fromHex(e.slice(0,c),a),d=v.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=I(i,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(w.ZERO)},ExtendedPoint:w,utils:{getExtendedPublicKey:C,randomPrivateKey:()=>i(r.BYTES),precompute:(e=8,t=w.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(Xa))(),Za=(()=>function(e){const t=(na(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,o=e=>da(e,n),s=t.montgomeryBits,i=Math.ceil(s/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>pa(e,n-BigInt(2),n));function u(e,t,r){const n=o(e*(t-r));return[t=o(t-n),r=o(r+n)]}const h=(t.a-BigInt(2))/BigInt(4);function d(e){return zi(o(e),i)}function p(e,t){const r=function(e){const t=Ki("u coordinate",e,i);return 32===a&&(t[31]&=127),ji(t)}(t),p=function(e){const t=Ki("scalar",e),r=t.length;if(r!==i&&r!==a)throw new Error("invalid scalar, expected "+i+" or "+a+" bytes, got "+r);return ji(c(t))}(e),f=function(e,t){Xi("u",e,Ua,n),Xi("scalar",t,Ua,n);const r=t,i=e;let a,c=Ma,d=Ua,p=e,f=Ma,g=Ua;for(let e=BigInt(s-1);e>=Ua;e--){const t=r>>e&Ma;g^=t,a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1],g=t;const n=c+d,s=o(n*n),l=c-d,m=o(l*l),y=s-m,b=p+f,w=o((p-f)*n),v=o(b*l),E=w+v,S=w-v;p=o(E*E),f=o(i*o(S*S)),c=o(s*m),d=o(y*(s+o(h*y)))}a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1];const m=l(d);return o(c*m)}(r,p);if(f===Ua)throw new Error("invalid private or public key received");return d(f)}const f=d(t.Gu);function g(e){return p(e,f)}return{scalarMult:p,scalarMultBase:g,getSharedSecret:(e,t)=>p(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:f}}({P:Fa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Fa,{pow_p_5_8:r,b2:n}=Ka(e);return da(fa(r,ja,t)*n,t)},adjustScalarBytes:Ga,randomBytes:Dr}))();function Qa(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}class ec{type="Ed25519";raw;constructor(e){this.raw=nc(e,32)}toMultihash(){return ct.digest(Wu(this))}toCID(){return yt.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}verify(e,t){return function(e,t,r){return Ya.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this.raw,t,e)}}class tc{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=nc(e,64),this.publicKey=new ec(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}sign(e){return function(e,t){const r=e.subarray(0,32);return Ya.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this.raw,e)}}function rc(e){return e=nc(e,32),new ec(e)}function nc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ws(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var oc,sc,ic,ac;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1"}(oc||(oc={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1"}(sc||(sc={})),function(e){e.codec=()=>wr(sc)}(oc||(oc={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),oc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.Type=oc.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ic||(ic={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),oc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.Type=oc.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ac||(ac={}));var cc=__webpack_require__(152);function lc(e,t){let r=0;if(1===e.length)return e[0];for(let n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function uc(e,t,r=-1){const n=r;let o=e,s=0,i=Math.pow(2,t);for(let r=1;r<8;r++){if(e<i){let e;if(n<0)e=new ArrayBuffer(r),s=r;else{if(n<r)return new ArrayBuffer(0);e=new ArrayBuffer(n),s=n}const i=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);i[s-e-1]=Math.floor(o/r),o-=i[s-e-1]*r}return e}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function hc(...e){let t=0,r=0;for(const r of e)t+=r.length;const n=new ArrayBuffer(t),o=new Uint8Array(n);for(const t of e)o.set(t,r),r+=t.length;return o}function dc(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];const n=lc(r,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let t=0;t<this.valueHex.byteLength;t++)s[t]=e[t];return s[0]&=127,lc(s,8)-n}function pc(e,t){const r=e.toString(10);if(t<r.length)return"";const n=t-r.length,o=new Array(n);for(let e=0;e<n;e++)o[e]="0";return o.join("").concat(r)}function fc(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function gc(e){let t=0,r=0;for(let r=0;r<e.length;r++)t+=e[r].byteLength;const n=new Uint8Array(t);for(let t=0;t<e.length;t++){const o=e[t];n.set(new Uint8Array(o),r),r+=o.byteLength}return n.buffer}function mc(e,t,r,n){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):n<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-n<0&&(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",1)):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}Math.log(2);class yc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return gc(this.items)}}const bc=[new Uint8Array([1])],wc="0123456789",vc=new ArrayBuffer(0),Ec=new Uint8Array(0),Sc="EndOfContent",Ac="OCTET STRING",kc="BIT STRING";function Cc(e){var t;return(t=class extends e{constructor(...e){var t;super(...e);const r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?cc._H.toUint8Array(r.valueHex):Ec}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}fromBER(e,t,r){const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!mc(this,n,t,r))return-1;const o=t+r;return this.valueHexView=n.subarray(t,o),this.valueHexView.length?(this.blockLength=r,o):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",vc)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:cc.U$.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class Ic{constructor({blockLength:e=0,error:t="",warnings:r=[],valueBeforeDecode:n=Ec}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=cc._H.toUint8Array(n)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:cc.U$.ToHex(this.valueBeforeDecodeView)}}}Ic.NAME="baseBlock";class xc extends Ic{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}xc.NAME="valueBlock";class Tc extends(Cc(Ic)){constructor({idBlock:e={}}={}){var t,r,n,o;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?cc._H.toUint8Array(e.valueHex):Ec,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(n=e.tagNumber)&&void 0!==n?n:-1,this.isConstructed=null!==(o=e.isConstructed)&&void 0!==o&&o):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",vc}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){const r=uc(this.tagNumber,7),n=new Uint8Array(r),o=r.byteLength,s=new Uint8Array(o+1);if(s[0]=31|t,!e){for(let e=0;e<o-1;e++)s[e+1]=128|n[e];s[o]=n[o-1]}return s.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){const n=cc._H.toUint8Array(e);if(!mc(this,n,t,r))return-1;const o=n.subarray(t,t+r);if(0===o.length)return this.error="Zero buffer length",-1;switch(192&o[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~o[0]),this.isHexOnly=!1;const s=31&o[0];if(31!==s)this.tagNumber=s,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&o[e];){if(t[e-1]=127&o[e],e++,e>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&o[e];const n=new Uint8Array(e);for(let r=0;r<e;r++)n[r]=t[r];t=this.valueHexView=new Uint8Array(e),t.set(n),this.blockLength<=9?this.tagNumber=lc(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Tc.NAME="identificationBlock";class _c extends Ic{constructor({lenBlock:e={}}={}){var t,r,n;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(n=e.length)&&void 0!==n?n:0}fromBER(e,t,r){const n=cc._H.toUint8Array(e);if(!mc(this,n,t,r))return-1;const o=n.subarray(t,t+r);if(0===o.length)return this.error="Zero buffer length",-1;if(255===o[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===o[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&o[0]),!1===this.longFormUsed)return this.length=o[0],this.blockLength=1,t+this.blockLength;const s=127&o[0];if(s>8)return this.error="Too big integer",-1;if(s+1>o.length)return this.error="End of input reached before message was fully decoded",-1;const i=t+1,a=n.subarray(i,i+s);return 0===a[s-1]&&this.warnings.push("Needlessly long encoded length"),this.length=lc(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),r[0]=128),t;if(this.longFormUsed){const n=uc(this.length,8);if(n.byteLength>127)return this.error="Too big length",vc;if(t=new ArrayBuffer(n.byteLength+1),e)return t;const o=new Uint8Array(n);r=new Uint8Array(t),r[0]=128|n.byteLength;for(let e=0;e<n.byteLength;e++)r[e+1]=o[e];return t}return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}_c.NAME="lengthBlock";const Nc={};class Pc extends Ic{constructor({name:e="",optional:t=!1,primitiveSchema:r,...n}={},o){super(n),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Tc(n),this.lenBlock=new _c(n),this.valueBlock=o?new o(n):new xc(n)}fromBER(e,t,r){const n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}toBER(e,t){const r=t||new yc;t||Lc(this);const n=this.idBlock.toBER(e);if(r.write(n),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const n=this.lenBlock.toBER(e);r.write(n),r.write(t)}return t?vc:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():cc.U$.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${cc.U$.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),n=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==n[e])return!1;return!0}(this.toBER(),e.toBER())}}function Lc(e){if(e instanceof Nc.Constructed)for(const t of e.valueBlock.value)Lc(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock.isIndefiniteForm}Pc.NAME="BaseBlock";class Bc extends Pc{constructor({value:e="",...t}={},r){super(t,r),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,r){const n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Bc.NAME="BaseStringBlock";class Oc extends(Cc(xc)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var Rc,Dc,Uc,Mc,Fc,$c,qc,Hc,jc,Vc,zc,Kc,Gc,Wc,Jc,Xc,Yc,Zc,Qc,el,tl,rl,nl,ol,sl,il,al,cl,ll,ul,hl,dl,pl;Oc.NAME="PrimitiveValueBlock";class fl extends Pc{constructor(e={}){super(e,Oc),this.idBlock.isConstructed=!1}}function gl(e,t=0,r=e.length){const n=t;let o=new Pc({},xc);const s=new Ic;if(!mc(s,e,t,r))return o.error=s.error,{offset:-1,result:o};if(!e.subarray(t,t+r).length)return o.error="Zero buffer length",{offset:-1,result:o};let i=o.idBlock.fromBER(e,t,r);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),-1===i)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=i,r-=o.idBlock.blockLength,i=o.lenBlock.fromBER(e,t,r),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),-1===i)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=i,r-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let a=Pc;if(1===o.idBlock.tagClass){if(o.idBlock.tagNumber>=37&&!1===o.idBlock.isHexOnly)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};a=Nc.EndOfContent;break;case 1:a=Nc.Boolean;break;case 2:a=Nc.Integer;break;case 3:a=Nc.BitString;break;case 4:a=Nc.OctetString;break;case 5:a=Nc.Null;break;case 6:a=Nc.ObjectIdentifier;break;case 10:a=Nc.Enumerated;break;case 12:a=Nc.Utf8String;break;case 13:a=Nc.RelativeObjectIdentifier;break;case 14:a=Nc.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:a=Nc.Sequence;break;case 17:a=Nc.Set;break;case 18:a=Nc.NumericString;break;case 19:a=Nc.PrintableString;break;case 20:a=Nc.TeletexString;break;case 21:a=Nc.VideotexString;break;case 22:a=Nc.IA5String;break;case 23:a=Nc.UTCTime;break;case 24:a=Nc.GeneralizedTime;break;case 25:a=Nc.GraphicString;break;case 26:a=Nc.VisibleString;break;case 27:a=Nc.GeneralString;break;case 28:a=Nc.UniversalString;break;case 29:a=Nc.CharacterString;break;case 30:a=Nc.BmpString;break;case 31:a=Nc.DATE;break;case 32:a=Nc.TimeOfDay;break;case 33:a=Nc.DateTime;break;case 34:a=Nc.Duration;break;default:{const e=o.idBlock.isConstructed?new Nc.Constructed:new Nc.Primitive;e.idBlock=o.idBlock,e.lenBlock=o.lenBlock,e.warnings=o.warnings,o=e}}}else a=o.idBlock.isConstructed?Nc.Constructed:Nc.Primitive;return o=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(o,a),i=o.fromBER(e,t,o.lenBlock.isIndefiniteForm?r:o.lenBlock.length),o.valueBeforeDecodeView=e.subarray(n,n+o.blockLength),{offset:i,result:o}}Rc=fl,Nc.Primitive=Rc,fl.NAME="PRIMITIVE";class ml extends xc{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=cc._H.toUint8Array(e);if(!mc(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let o=t;for(;(this.isIndefiniteForm?1:r)>0;){const e=gl(n,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===Sc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Sc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){const r=t||new yc;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?vc:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}ml.NAME="ConstructedValueBlock";class yl extends Pc{constructor(e={}){super(e,ml),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map((e=>` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Dc=yl,Nc.Constructed=Dc,yl.NAME="CONSTRUCTED";class bl extends xc{fromBER(e,t,r){return t}toBER(e){return vc}}bl.override="EndOfContentValueBlock";class wl extends Pc{constructor(e={}){super(e,bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Uc=wl,Nc.EndOfContent=Uc,wl.NAME=Sc;class vl extends Pc{constructor(e={}){super(e,xc),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){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Mc=vl,Nc.Null=Mc,vl.NAME="NULL";class El extends(Cc(xc)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=cc._H.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,r){const n=cc._H.toUint8Array(e);return mc(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,dc.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}El.NAME="BooleanValueBlock";class Sl extends Pc{constructor(e={}){super(e,El),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}`}}Fc=Sl,Nc.Boolean=Fc,Sl.NAME="BOOLEAN";class Al extends(Cc(ml)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,n=ml.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===Sc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Ac)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,n=super.fromBER(e,t,r),this.blockLength=r;return n}toBER(e,t){return this.isConstructed?ml.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Al.NAME="OctetStringValueBlock";class kl extends Pc{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,o;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(o=r.value)||void 0===o?void 0:o.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Al),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const n=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(n.byteLength){const e=gl(n,0,n.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch(e){}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?yl.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${cc.U$.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof kl&&e.push(t.valueBlock.valueHexView);return cc._H.concat(e)}}$c=kl,Nc.OctetString=$c,kl.NAME=Ac;class Cl extends(Cc(ml)){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let n=-1;if(this.isConstructed){if(n=ml.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(const e of this.value){const t=e.constructor.NAME;if(t===Sc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==kc)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const r=e.valueBlock;if(this.unusedBits>0&&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}const o=cc._H.toUint8Array(e);if(!mc(this,o,t,r))return-1;const s=o.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){const e=s.subarray(1);try{if(e.byteLength){const t=gl(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 ml.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return vc;const 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}}}Cl.NAME="BitStringValueBlock";class Il extends Pc{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,o;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(o=r.value)||void 0===o?void 0:o.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Cl),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 yl.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function xl(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),o=new Uint8Array(t);let s=n.slice(0);const i=s.length-1,a=o.slice(0),c=a.length-1;let l=0,u=0;for(let e=c<i?i:c;e>=0;e--,u++)l=1==u<a.length?s[i-u]+a[c-u]+r[0]:s[i-u]+r[0],r[0]=l/10,1==u>=s.length?s=hc(new Uint8Array([l%10]),s):s[i-u]=l%10;return r[0]>0&&(s=hc(r,s)),s}function Tl(e){if(e>=bc.length)for(let t=bc.length;t<=e;t++){const e=new Uint8Array([0]);let r=bc[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=hc(e,r)),bc.push(r)}return bc[e]}function _l(e,t){let r=0;const n=new Uint8Array(e),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=s[i-u]-a[c-u]-r,1==l<0?(r=1,s[i-u]=l+10):(r=0,s[i-u]=l);if(r>0)for(let e=i-c+1;e>=0;e--,u++){if(l=s[i-u]-r,!(l<0)){r=0,s[i-u]=l;break}r=1,s[i-u]=l+10}return s.slice()}qc=Il,Nc.BitString=qc,Il.NAME=kc;class Nl extends(Cc(xc)){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=dc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){const e=uc(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let o=uc(t,8,n),s=new Uint8Array(o);if(128&s[0]){const e=o.slice(0),t=new Uint8Array(e);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let r=0;r<e.byteLength;r++)s[r+1]=t[r];s[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,n=0){const o=this.fromBER(e,t,r);if(-1===o)return o;const s=this.valueHexView;return 0===s[0]&&128&s[1]?this.valueHexView=s.subarray(1):0!==n&&s.length<n&&(n-s.length>1&&(n=s.length+1),this.valueHexView=s.subarray(n-s.length)),o}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const 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]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const 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(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),n=0;const o=this.valueHexView;let s="",i=!1;for(let i=o.byteLength-1;i>=0;i--){t=o[i];for(let o=0;o<8;o++)1&~t||(n===e?(r=_l(Tl(n),r),s="-"):r=xl(r,Tl(n))),n++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(i=!0),i&&(s+=wc.charAt(r[e]));return!1===i&&(s+=wc.charAt(0)),s}}Hc=Nl,Nl.NAME="IntegerValueBlock",Object.defineProperty(Hc.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Pl extends Pc{constructor(e={}){super(e,Nl),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return fc(),BigInt(this.valueBlock.toString())}static fromBigInt(e){fc();const t=BigInt(e),r=new yc,n=t.toString(16).replace(/^-/,""),o=new Uint8Array(cc.U$.FromHex(n));if(t<0){const e=new Uint8Array(o.length+(128&o[0]?1:0));e[0]|=128;const n=BigInt(`0x${cc.U$.ToHex(e)}`)+t,s=cc._H.toUint8Array(cc.U$.FromHex(n.toString(16)));s[0]|=128,r.write(s)}else 128&o[0]&&r.write(new Uint8Array([0])),r.write(o);return new Pl({valueHex:r.final()})}convertToDER(){const e=new Pl({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Pl({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}jc=Pl,Nc.Integer=jc,Pl.NAME="INTEGER";class Ll extends Pl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Vc=Ll,Nc.Enumerated=Vc,Ll.NAME="ENUMERATED";class Bl extends(Cc(xc)){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const n=cc._H.toUint8Array(e);if(!mc(this,n,t,r))return-1;const o=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&o[e],this.blockLength++,128&o[e]);e++);const s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return this.valueHexView=s,128&o[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=lc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){fc();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=uc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",vc;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),n=t.byteLength-1;for(let t=0;t<n;t++)r[t]=128|e[t];r[n]=e[n]}return r}toString(){let e="";if(this.isHexOnly)e=cc.U$.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Bl.NAME="sidBlock";class Ol extends xc{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let n=t;for(;r>0;){const t=new Bl;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const n=this.value[r].toBER(e);if(0===n.byteLength)return this.error=this.value[r].error,vc;t.push(n)}return gc(t)}fromString(e){this.value=[];let t=0,r=0,n="",o=!1;do{if(r=e.indexOf(".",t),n=-1===r?e.substring(t):e.substring(t,r),t=r+1,o){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const r=parseInt(n,10);if(isNaN(r))return;e.valueDec=r+t,o=!1}else{const e=new Bl;if(n>Number.MAX_SAFE_INTEGER){fc();const t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,o=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();0!==r&&(e=`${e}.`),t?(n=`{${n}}`,this.value[r].isFirstSid?e=`2.{${n} - 80}`:e+=n):e+=n}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ol.NAME="ObjectIdentifierValueBlock";class Rl extends Pc{constructor(e={}){super(e,Ol),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}zc=Rl,Nc.ObjectIdentifier=zc,Rl.NAME="OBJECT IDENTIFIER";class Dl extends(Cc(Ic)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const n=cc._H.toUint8Array(e);if(!mc(this,n,t,r))return-1;const o=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&o[e],this.blockLength++,128&o[e]);e++);const s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return this.valueHexView=s,128&o[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=lc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=uc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",vc;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),n=t.byteLength-1;for(let t=0;t<n;t++)r[t]=128|e[t];r[n]=e[n]}return r.buffer}toString(){let e="";return e=this.isHexOnly?cc.U$.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Dl.NAME="relativeSidBlock";class Ul extends xc{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let n=t;for(;r>0;){const t=new Dl;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){const r=[];for(let t=0;t<this.value.length;t++){const n=this.value[t].toBER(e);if(0===n.byteLength)return this.error=this.value[t].error,vc;r.push(n)}return gc(r)}fromString(e){this.value=[];let t=0,r=0,n="";do{r=e.indexOf(".",t),n=-1===r?e.substring(t):e.substring(t,r),t=r+1;const o=new Dl;if(o.valueDec=parseInt(n,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();0!==r&&(e=`${e}.`),t?(n=`{${n}}`,e+=n):e+=n}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ul.NAME="RelativeObjectIdentifierValueBlock";class Ml extends Pc{constructor(e={}){super(e,Ul),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Kc=Ml,Nc.RelativeObjectIdentifier=Kc,Ml.NAME="RelativeObjectIdentifier";class Fl extends yl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Gc=Fl,Nc.Sequence=Gc,Fl.NAME="SEQUENCE";class $l extends yl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}Wc=$l,Nc.Set=Wc,$l.NAME="SET";class ql extends(Cc(xc)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=""}toJSON(){return{...super.toJSON(),value:this.value}}}ql.NAME="StringValueBlock";class Hl extends ql{}Hl.NAME="SimpleStringValueBlock";class jl extends Bc{constructor({...e}={}){super(e,Hl)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,cc._H.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);this.valueBlock.value=e}}jl.NAME="SIMPLE STRING";class Vl extends jl{fromBuffer(e){this.valueBlock.valueHexView=cc._H.toUint8Array(e);try{this.valueBlock.value=cc.U$.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=cc.U$.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(cc.U$.FromUtf8String(e)),this.valueBlock.value=e}}Vl.NAME="Utf8StringValueBlock";class zl extends Vl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Jc=zl,Nc.Utf8String=Jc,zl.NAME="UTF8String";class Kl extends jl{fromBuffer(e){this.valueBlock.value=cc.U$.ToUtf16String(e),this.valueBlock.valueHexView=cc._H.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(cc.U$.FromUtf16String(e))}}Kl.NAME="BmpStringValueBlock";class Gl extends Kl{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Xc=Gl,Nc.BmpString=Xc,Gl.NAME="BMPString";class Wl extends jl{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let n=0;n<t;n++){const t=uc(e.charCodeAt(n),8),o=new Uint8Array(t);if(o.length>4)continue;const s=4-o.length;for(let e=o.length-1;e>=0;e--)r[4*n+e+s]=o[e]}this.valueBlock.value=e}}Wl.NAME="UniversalStringValueBlock";class Jl extends Wl{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Yc=Jl,Nc.UniversalString=Yc,Jl.NAME="UniversalString";class Xl extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Zc=Xl,Nc.NumericString=Zc,Xl.NAME="NumericString";class Yl extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Qc=Yl,Nc.PrintableString=Qc,Yl.NAME="PrintableString";class Zl extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}el=Zl,Nc.TeletexString=el,Zl.NAME="TeletexString";class Ql extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}tl=Ql,Nc.VideotexString=tl,Ql.NAME="VideotexString";class eu extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}rl=eu,Nc.IA5String=rl,eu.NAME="IA5String";class tu extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}nl=tu,Nc.GraphicString=nl,tu.NAME="GraphicString";class ru extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}ol=ru,Nc.VisibleString=ol,ru.NAME="VisibleString";class nu extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}sl=nu,Nc.GeneralString=sl,nu.NAME="GeneralString";class ou extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}il=ou,Nc.CharacterString=il,ou.NAME="CharacterString";class su extends ru{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<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,cc._H.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const r=parseInt(t[1],10);this.year=r>=50?1900+r: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){const e=new Array(7);return e[0]=pc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=pc(this.month,2),e[2]=pc(this.day,2),e[3]=pc(this.hour,2),e[4]=pc(this.minute,2),e[5]=pc(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}}}al=su,Nc.UTCTime=al,su.NAME="UTCTime";class iu extends su{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="",o="",s=0,i=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new 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 new Error("Wrong input string for conversion");let o=parseInt(r.substring(0,2),10);if(isNaN(o.valueOf()))throw new Error("Wrong input string for conversion");if(i=e*o,4===r.length){if(o=parseInt(r.substring(2,4),10),isNaN(o.valueOf()))throw new Error("Wrong input string for conversion");a=e*o}}}let c=n.indexOf(".");if(-1===c&&(c=n.indexOf(",")),-1!==c){const e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");s=e.valueOf(),o=n.substring(0,c)}else o=n;switch(!0){case 8===o.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===o.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){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===o.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*s;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===o.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*s;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(o);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+i;break;case 5:this.minute=parseInt(l[e],10)+a;break;case 6:this.second=parseInt(l[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(pc(this.year,4)),e.push(pc(this.month,2)),e.push(pc(this.day,2)),e.push(pc(this.hour,2)),e.push(pc(this.minute,2)),e.push(pc(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(pc(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}cl=iu,Nc.GeneralizedTime=cl,iu.NAME="GeneralizedTime";class au extends zl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ll=au,Nc.DATE=ll,au.NAME="DATE";class cu extends zl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ul=cu,Nc.TimeOfDay=ul,cu.NAME="TimeOfDay";class lu extends zl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}hl=lu,Nc.DateTime=hl,lu.NAME="DateTime";class uu extends zl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}dl=uu,Nc.Duration=dl,uu.NAME="Duration";class hu extends zl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}pl=hu,Nc.TIME=pl,hu.NAME="TIME";class du extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class pu extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class fu extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const gu={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new fu("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};class mu{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=bu(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return yt.createV1(114,this._multihash)}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}verify(e,t){return async function(e,t,r){const n=await gu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return gu.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}}class yu{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return null==this._raw&&(this._raw=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 Ws("JWK was missing components");const t=new Fl({value:[new Pl({value:0}),Pl.fromBigInt(vu(xt(e.n,"base64url"))),Pl.fromBigInt(vu(xt(e.e,"base64url"))),Pl.fromBigInt(vu(xt(e.d,"base64url"))),Pl.fromBigInt(vu(xt(e.p,"base64url"))),Pl.fromBigInt(vu(xt(e.q,"base64url"))),Pl.fromBigInt(vu(xt(e.dp,"base64url"))),Pl.fromBigInt(vu(xt(e.dq,"base64url"))),Pl.fromBigInt(vu(xt(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}sign(e){return async function(e,t){const r=await gu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await gu.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}}function bu(e){if(null==e.n||null==e.e)throw new Ws("JWK was missing components");const t=new Fl({value:[new Fl({value:[new Rl({value:"1.2.840.113549.1.1.1"}),new vl]}),new Il({valueHex:new Fl({value:[Pl.fromBigInt(vu(xt(e.n,"base64url"))),Pl.fromBigInt(vu(xt(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function wu(e){let t=e.valueBlock.valueHexView;for(;0===t[0];)t=t.subarray(1);return Zr(t,"base64url")}function vu(e){const t=[];return e.forEach((function(e){let r=e.toString(16);r.length%2>0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}function Eu(e){const t=function(e){const{result:t}=function(e){if(!e.byteLength){const e=new Pc({},xc);return e.error="Input buffer has zero length",{offset:-1,result:e}}return gl(cc._H.toUint8Array(e).slice(),0,e.byteLength)}(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:wu(r[0]),e:wu(r[1])}}(e);if(function(e){if("RSA"!==e.kty)throw new Ws("invalid key type");if(null==e.n)throw new Ws("invalid key modulus");return 8*xt(e.n,"base64url").length}(t)>8192)throw new Js("Key size is too large");const r=ot(18,jr(ic.encode({Type:oc.RSA,Data:e})));return new mu(t,r)}class Su extends Or{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Tr(e);const r=Br(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),o.fill(0)}update(e){return _r(this),this.iHash.update(e),this}digestInto(e){_r(this),xr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:s,outputLen:i}=this;return e.finished=n,e.destroyed=o,e.blockLen=s,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Au=(e,t,r)=>new Su(e,t).update(r).digest();function ku(e){void 0!==e.lowS&&Oi("lowS",e.lowS),void 0!==e.prehash&&Oi("prehash",e.prehash)}Au.create=(e,t)=>new Su(e,t);const{Ph:Cu,aT:Iu}=f;class xu extends Error{constructor(e=""){super(e)}}const Tu={Err:xu,_tlv:{encode:(e,t)=>{const{Err:r}=Tu;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,o=Ui(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Ui(o.length/2|128):"";return Ui(e)+s+o+t},decode(e,t){const{Err:r}=Tu;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const o=t[n++];let s=0;if(128&o){const e=127&o;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(n,n+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=o;const i=t.subarray(n,n+s);if(i.length!==s)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=Tu;if(e<_u)throw new t("integer: negative integers are not allowed");let r=Ui(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=Tu;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Cu(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=Tu,o="string"==typeof e?Iu(e):e;Bi(o);const{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=Tu,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},_u=BigInt(0),Nu=BigInt(1),Pu=(BigInt(2),BigInt(3));function Lu(e){const t=function(e){const t=Pa(e);return na(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,o=r.BYTES+1,s=2*r.BYTES+1;function i(e){return da(e,n)}function a(e){return ga(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=Pa(e);na(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=ba(t.n,t.nBitLength),o=t.toBytes||((e,t,n)=>{const o=t.toAffine();return Gi(Uint8Array.from([4]),r.toBytes(o.x),r.toBytes(o.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:n,b:o}=t,s=r.sqr(e),i=r.mul(s,e);return r.add(r.add(i,r.mul(e,n)),o)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:o,n:s}=t;if(r&&"bigint"!=typeof e){if(Li(e)&&(e=Di(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*n,"0")}let i;try{i="bigint"==typeof e?e:Hi(Ki("private key",e,n))}catch(t){throw new Error("invalid private key, expected hex or "+n+" bytes, got "+typeof e)}return o&&(i=da(i,s)),Xi("private key",i,Nu,s),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=oa(((e,t)=>{const{px:n,py:o,pz:s}=e;if(r.eql(s,r.ONE))return{x:n,y:o};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(s));const a=r.mul(n,t),c=r.mul(o,t),l=r.mul(s,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),u=oa((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not FE");const s=r.sqr(o),a=i(n);if(!r.eql(s,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t))throw new Error("y required");if(null==n||!r.isValid(n))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const o=e=>r.eql(e,r.ZERO);return o(t)&&o(n)?h.ZERO:new h(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(s(Ki("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return Na(h,n,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:o}=this,{px:s,py:i,pz:a}=e,l=r.eql(r.mul(t,a),r.mul(s,o)),u=r.eql(r.mul(n,a),r.mul(i,o));return l&&u}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,o=r.mul(n,Pu),{px:s,py:i,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(s,s),p=r.mul(i,i),f=r.mul(a,a),g=r.mul(s,i);return g=r.add(g,g),u=r.mul(s,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(o,f),l=r.add(c,l),c=r.sub(p,l),l=r.add(p,l),l=r.mul(c,l),c=r.mul(g,c),u=r.mul(o,u),f=r.mul(e,f),g=r.sub(d,f),g=r.mul(e,g),g=r.add(g,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,g),l=r.add(l,d),f=r.mul(i,a),f=r.add(f,f),d=r.mul(f,g),c=r.sub(c,d),u=r.mul(f,p),u=r.add(u,u),u=r.add(u,u),new h(c,l,u)}add(e){c(e);const{px:n,py:o,pz:s}=this,{px:i,py:a,pz:l}=e;let u=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Pu);let m=r.mul(n,i),y=r.mul(o,a),b=r.mul(s,l),w=r.add(n,o),v=r.add(i,a);w=r.mul(w,v),v=r.add(m,y),w=r.sub(w,v),v=r.add(n,s);let E=r.add(i,l);return v=r.mul(v,E),E=r.add(m,b),v=r.sub(v,E),E=r.add(o,s),u=r.add(a,l),E=r.mul(E,u),u=r.add(y,b),E=r.sub(E,u),p=r.mul(f,v),u=r.mul(g,b),p=r.add(u,p),u=r.sub(y,p),p=r.add(y,p),d=r.mul(u,p),y=r.add(m,m),y=r.add(y,m),b=r.mul(f,b),v=r.mul(g,v),y=r.add(y,b),b=r.sub(m,b),b=r.mul(f,b),v=r.add(v,b),m=r.mul(y,v),d=r.add(d,m),m=r.mul(E,v),u=r.mul(w,u),u=r.sub(u,m),m=r.mul(w,y),p=r.mul(E,p),p=r.add(p,m),new h(u,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:n,n:o}=t;Xi("scalar",e,_u,o);const s=h.ZERO;if(e===_u)return s;if(this.is0()||e===Nu)return this;if(!n||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:i,k1:a,k2neg:c,k2:l}=n.splitScalar(e),u=s,d=s,f=this;for(;a>_u||l>_u;)a&Nu&&(u=u.add(f)),l&Nu&&(d=d.add(f)),f=f.double(),a>>=Nu,l>>=Nu;return i&&(u=u.negate()),c&&(d=d.negate()),d=new h(r.mul(d.px,n.beta),d.py,d.pz),u.add(d)}multiply(e){const{endo:n,n:o}=t;let s,i;if(Xi("scalar",e,Nu,o),n){const{k1neg:t,k1:o,k2neg:a,k2:c}=n.splitScalar(e);let{p:l,f:u}=this.wNAF(o),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(t,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,n.beta),d.py,d.pz),s=l.add(d),i=u.add(f)}else{const{p:t,f:r}=this.wNAF(e);s=t,i=r}return h.normalizeZ([s,i])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,o=(e,t)=>t!==_u&&t!==Nu&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=o(this,t).add(o(e,r));return s.is0()?void 0:s}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Nu)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===Nu?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Oi("isCompressed",e),this.assertValidity(),o(h,this,e)}toHex(e=!0){return Oi("isCompressed",e),Di(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const d=t.nBitLength,p=_a(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:i,isWithinCurveOrder:function(e){return Ji(e,Nu,t.n)}}}({...t,toBytes(e,t,n){const o=t.toAffine(),s=r.toBytes(o.x),i=Gi;return Oi("isCompressed",n),n?i(Uint8Array.from([t.hasEvenY()?2:3]),s):i(Uint8Array.from([4]),s,r.toBytes(o.y))},fromBytes(e){const t=e.length,n=e[0],i=e.subarray(1);if(t!==o||2!==n&&3!==n){if(t===s&&4===n)return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))};throw new Error("invalid Point, expected length of "+o+", or uncompressed "+s+", got "+t)}{const e=Hi(i);if(!Ji(e,Nu,r.ORDER))throw new Error("Point is not on curve");const t=u(e);let o;try{o=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~n)!=((o&Nu)===Nu)&&(o=r.neg(o)),{x:e,y:o}}}}),d=e=>Di(Vi(e,t.nByteLength));function p(e){return e>n>>Nu}const f=(e,t,r)=>Hi(e.slice(t,r));class g{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Ki("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Tu.toSig(Ki("DER",e));return new g(t,r)}assertValidity(){Xi("r",this.r,Nu,n),Xi("s",this.s,Nu,n)}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s:o,recovery:s}=this,l=w(Ki("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw new Error("recovery id invalid");const u=2===s||3===s?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&s?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=i(-l*f),m=i(o*f),y=c.BASE.multiplyAndAddUnsafe(p,g,m);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return qi(this.toDERHex())}toDERHex(){return Tu.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qi(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const m={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=va(t.n);return function(e,t,r=!1){const n=e.length,o=wa(t),s=va(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=da(r?ji(e):Hi(e),t-ia)+ia;return r?zi(i,o):Vi(i,o)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function y(e){const t=Li(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===o||n===s:r?n===2*o||n===2*s:e instanceof c}const b=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const r=Hi(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return i(b(e))},v=Zi(t.nBitLength);function E(e){return Xi("num < 2^"+t.nBitLength,e,_u,v),Vi(e,t.nByteLength)}const S={lowS:t.lowS,prehash:!1},A={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(y(e))throw new Error("first arg must be private key");if(!y(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(r)},sign:function(e,n,o=S){const{seed:s,k2sig:u}=function(e,n,o=S){if(["recovered","canonical"].some((e=>e in o)))throw new Error("sign() legacy options not supported");const{hash:s,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:m}=o;null==d&&(d=!0),e=Ki("msgHash",e),ku(o),f&&(e=Ki("prehashed msgHash",s(e)));const y=w(e),v=l(n),A=[E(v),E(y)];if(null!=m&&!1!==m){const e=!0===m?u(r.BYTES):m;A.push(Ki("extraEntropy",e))}const k=Gi(...A),C=y;return{seed:k,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),o=i(n.x);if(o===_u)return;const s=i(r*i(C+o*v));if(s===_u)return;let l=(n.x===o?0:2)|Number(n.y&Nu),u=s;return d&&p(s)&&(u=function(e){return p(e)?i(-e):e}(s),l^=1),new g(o,u,l)}}}(e,n,o),d=t;return ta(d.hash.outputLen,d.nByteLength,d.hmac)(s,u)},verify:function(e,r,n,o=A){const s=e;r=Ki("msgHash",r),n=Ki("publicKey",n);const{lowS:l,prehash:u,format:h}=o;if(ku(o),"strict"in o)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const d="string"==typeof s||Li(s),p=!d&&!h&&"object"==typeof s&&null!==s&&"bigint"==typeof s.r&&"bigint"==typeof s.s;if(!d&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let f,m;try{if(p&&(f=new g(s.r,s.s)),d){try{"compact"!==h&&(f=g.fromDER(s))}catch(e){if(!(e instanceof Tu.Err))throw e}f||"der"===h||(f=g.fromCompact(s))}m=c.fromHex(n)}catch(e){return!1}if(!f)return!1;if(l&&f.hasHighS())return!1;u&&(r=t.hash(r));const{r:y,s:b}=f,v=w(r),E=a(b),S=i(v*E),k=i(y*E),C=c.BASE.multiplyAndAddUnsafe(m,S,k)?.toAffine();return!!C&&i(C.x)===y},ProjectivePoint:c,Signature:g,utils:m}}function Bu(e){return{hash:e,hmac:(t,...r)=>Au(e,t,function(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];xr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const o=e[t];r.set(o,n),n+=o.length}return r}(...r)),randomBytes:Dr}}BigInt(4);const Ou=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ru=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Du=BigInt(1),Uu=BigInt(2),Mu=(e,t)=>(e+t/Uu)/t;const Fu=ba(Ou,void 0,void 0,{sqrt:function(e){const t=Ou,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=fa(u,r,t)*u%t,d=fa(h,r,t)*u%t,p=fa(d,Uu,t)*l%t,f=fa(p,o,t)*p%t,g=fa(f,s,t)*f%t,m=fa(g,a,t)*g%t,y=fa(m,c,t)*m%t,b=fa(y,a,t)*g%t,w=fa(b,r,t)*u%t,v=fa(w,i,t)*f%t,E=fa(v,n,t)*l%t,S=fa(E,Uu,t);if(!Fu.eql(Fu.sqr(S),e))throw new Error("Cannot find square root");return S}}),$u=function(e,t){const r=t=>Lu({...e,...Bu(t)});return{...r(t),create:r}}({a:BigInt(0),b:BigInt(7),Fp:Fu,n:Ru,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ru,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Du*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Mu(s*e,t),c=Mu(-n*e,t);let l=da(e-a*r-c*o,t),u=da(-a*n-c*s,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},jr);function qu(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}BigInt(0),$u.ProjectivePoint;class Hu{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return $u.ProjectivePoint.fromHex(e),e}catch(e){throw new Js(String(e))}}(e),this.raw=function(e){return $u.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return ct.digest(Wu(this))}toCID(){return yt.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}verify(e,t){return function(e,t,r){const n=dt.digest(r instanceof Uint8Array?r:r.subarray());if(qu(n))return n.then((({digest:r})=>$u.verify(t,r,e))).catch((e=>{throw new pu(String(e))}));try{return $u.verify(t,n.digest,e)}catch(e){throw new pu(String(e))}}(this._key,t,e)}}class ju{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=function(e){try{return $u.getPublicKey(e,!0),e}catch(e){throw new Xs(String(e))}}(e),this.publicKey=new Hu(t??function(e){try{return $u.getPublicKey(e,!0)}catch(e){throw new Xs(String(e))}}(e))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}sign(e){return function(e,t){const r=dt.digest(t instanceof Uint8Array?t:t.subarray());if(qu(r))return r.then((({digest:t})=>$u.sign(t,e).toDERRawBytes())).catch((e=>{throw new du(String(e))}));try{return $u.sign(r.digest,e).toDERRawBytes()}catch(e){throw new du(String(e))}}(this.raw,e)}}function Vu(e){return new Hu(e)}async function zu(e,t){if("Ed25519"===e)return async function(){const{privateKey:e,publicKey:t}=function(){const e=Ya.utils.randomPrivateKey(),t=Ya.getPublicKey(e);return{privateKey:Qa(e,t),publicKey:t}}();return new tc(e,t)}();if("secp256k1"===e)return async function(){const e=$u.utils.randomPrivateKey();return new ju(e)}();if("RSA"===e)return async function(e){if(e>8192)throw new Ws("Key size is too large");const t=await async function(e){const t=await gu.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 async function(e){if(null==e.privateKey||null==e.publicKey)throw new Ws("Private and public key are required");return Promise.all([gu.get().subtle.exportKey("jwk",e.privateKey),gu.get().subtle.exportKey("jwk",e.publicKey)])}(t);return{privateKey:r[0],publicKey:r[1]}}(e),r=ot(18,jr(ic.encode({Type:oc.RSA,Data:bu(t.publicKey)})));return new yu(t.privateKey,new mu(t.publicKey,r))}(t??2048);throw new yi}async function Ku(e,t){if("Ed25519"!==e)throw new yi("Seed key derivation only supported for Ed25519 keys");return async function(e){const{privateKey:t,publicKey:r}=function(e){if(32!==e.length)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=Ya.getPublicKey(t);return{privateKey:Qa(t,r),publicKey:r}}(e);return new tc(t,r)}(t)}function Gu(e){const{Type:t,Data:r}=ic.decode(e),n=r??new Uint8Array;switch(t){case oc.RSA:return Eu(n);case oc.Ed25519:return rc(n);case oc.secp256k1:return Vu(n);default:throw new yi}}function Wu(e){return ic.encode({Type:oc[e.type],Data:e.raw})}const Ju=Symbol.for("@libp2p/service-capabilities"),Xu=Symbol.for("@libp2p/service-dependencies"),Yu=Symbol.for("nodejs.util.inspect.custom");class Zu{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Fo]=!0;toString(){return null==this.string&&(this.string=Se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return yt.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Cn(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Cn(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Yu](){return`PeerId(${this.toString()})`}}class Qu extends Zu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class eh extends Zu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class th extends Zu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class rh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ct.digest(xt(this.url))}[Yu](){return`PeerId(${this.url})`}[Fo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return yt.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Zr(e)),e.toString()===this.toString())}}function nh(e,t){let r;if("1"===e.charAt(0)||"Q"===e.charAt(0))r=st(Se.decode(`z${e}`));else{if(null==t)throw new Ws('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=st(t.decode(e))}return sh(r)}function oh(e){if("Ed25519"===e.type)return new eh({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new th({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Qu({multihash:e.toCID().multihash,publicKey:e});throw new yi}function sh(e){if(function(e){return e.code===dt.code}(e))return new Qu({multihash:e});if(function(e){return e.code===ct.code}(e))try{const t=function(e){const{Type:t,Data:r}=ic.decode(e.digest),n=r??new Uint8Array;switch(t){case oc.Ed25519:return rc(n);case oc.secp256k1:return Vu(n);default:throw new yi}}(e);if("Ed25519"===t.type)return new eh({multihash:e,publicKey:t});if("secp256k1"===t.type)return new th({multihash:e,publicKey:t})}catch(t){const r=Zr(e.digest);return new rh(new URL(r))}throw new ai("Supplied PeerID Multihash is invalid")}function ih(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new ii("Supplied PeerID CID is invalid");if(2336===e.code){const t=Zr(e.multihash.digest);return new rh(new URL(t))}return sh(e.multihash)}class ah extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}}async function ch(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new ah(r?.errorMessage,r?.errorCode,r?.errorName));let n;const o=new ah(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(o)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class lh{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=$n(),this.haveNext=$n()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=$n(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch((()=>{})),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 new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=$n(),await ch(this.readNext.promise,t?.signal,t)}}class uh extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}class hh extends Error{code;constructor(e,t){super(e),this.code=t}}class dh extends hh{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}}function ph(e,t){const r=new lh;e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const 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]());const o=new _n,s={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const s=new Promise(((e,n)=>{r=()=>{n(new dh("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),s]);return!0===e?new _n:t}for(;o.byteLength<e;){const{value:e,done:t}=await Promise.race([n.next(),s]);if(!0===t)throw new uh("unexpected end of input");o.append(e)}const t=o.sublist(0,e);return o.consume(e),t}finally{null!=r&&t?.signal?.removeEventListener("abort",r)}},write:async(e,t)=>{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(o.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield o:yield*o,yield*r}()}return e}};return s}class fh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class gh extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class mh extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function yh(e,t={}){const r=ph(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=I(t.maxDataLength));const n=t?.lengthDecoder??N,o=t?.lengthEncoder??_;return{read:async e=>{let o=-1;const s=new _n;for(;;){s.append(await r.read(1,e));try{o=n(s)}catch(e){if(e instanceof RangeError)continue;throw e}if(o<0)throw new fh("Invalid message length");if(null!=t?.maxLengthLength&&s.byteLength>t.maxLengthLength)throw new mh("message length length too long");if(o>-1)break}if(null!=t?.maxDataLength&&o>t.maxDataLength)throw new gh("message length too long");return r.read(o,e)},write:async(e,t)=>{await r.write(new _n(o(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new _n(...e.flatMap((e=>[o(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function bh(){const e=$n();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const wh=65535,vh=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Eh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Sh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Ah(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function kh(e,...t){if(!Ah(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ch(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Ih=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function xh(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Ah(e))throw new Error("Uint8Array expected, got "+typeof e);e=Nh(e)}return e}const Th=(e,t)=>(Object.assign(t,e),t);function _h(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}function Nh(e){return Uint8Array.from(e)}function Ph(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Lh=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Bh=Lh("expand 16-byte k"),Oh=Lh("expand 32-byte k"),Rh=Ih(Bh),Dh=Ih(Oh);function Uh(e,t){return e<<t|e>>>32-t}function Mh(e){return e.byteOffset%4==0}Dh.slice();const Fh=2**32-1,$h=new Uint32Array;function qh(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Eh(o),Eh(i),Sh(s),Sh(r),(t,a,c,l,u=0)=>{kh(t),kh(a),kh(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),kh(l),Eh(u),u<0||u>=Fh)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p,f,g=t.length;if(32===g)d.push(p=Nh(t)),f=Dh;else{if(16!==g||!r)throw new Error(`arx: invalid 32-byte key, got length=${g}`);p=new Uint8Array(32),p.set(t),p.set(t,16),f=Rh,d.push(p)}Mh(a)||d.push(a=Nh(a));const m=Ih(p);if(n){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");n(f,m,Ih(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-o;if(y!==a.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,s?0:12-a.length),a=e,d.push(a)}const b=Ih(a);return function(e,t,r,n,o,s,i,a){const c=o.length,l=new Uint8Array(64),u=Ih(l),h=Mh(o)&&Mh(s),d=h?Ih(o):$h,p=h?Ih(s):$h;for(let f=0;f<c;i++){if(e(t,r,n,u,i,a),i>=Fh)throw new Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t<g;t++)e=f+t,s[e]=o[e]^l[t];f+=g}}}(e,f,m,b,c,l,u,i),Ph(...d),l}}const Hh=(e,t)=>255&e[t++]|(255&e[t++])<<8;class jh{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,kh(e=xh(e),32);const t=Hh(e,0),r=Hh(e,2),n=Hh(e,4),o=Hh(e,6),s=Hh(e,8),i=Hh(e,10),a=Hh(e,12),c=Hh(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|o<<9),this.r[4]=255&(o>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>14|i<<2),this.r[7]=8065&(i>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Hh(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:o,r:s}=this,i=s[0],a=s[1],c=s[2],l=s[3],u=s[4],h=s[5],d=s[6],p=s[7],f=s[8],g=s[9],m=Hh(e,t+0),y=Hh(e,t+2),b=Hh(e,t+4),w=Hh(e,t+6),v=Hh(e,t+8),E=Hh(e,t+10),S=Hh(e,t+12),A=Hh(e,t+14);let k=o[0]+(8191&m),C=o[1]+(8191&(m>>>13|y<<3)),I=o[2]+(8191&(y>>>10|b<<6)),x=o[3]+(8191&(b>>>7|w<<9)),T=o[4]+(8191&(w>>>4|v<<12)),_=o[5]+(v>>>1&8191),N=o[6]+(8191&(v>>>14|E<<2)),P=o[7]+(8191&(E>>>11|S<<5)),L=o[8]+(8191&(S>>>8|A<<8)),B=o[9]+(A>>>5|n),O=0,R=O+k*i+C*(5*g)+I*(5*f)+x*(5*p)+T*(5*d);O=R>>>13,R&=8191,R+=_*(5*h)+N*(5*u)+P*(5*l)+L*(5*c)+B*(5*a),O+=R>>>13,R&=8191;let D=O+k*a+C*i+I*(5*g)+x*(5*f)+T*(5*p);O=D>>>13,D&=8191,D+=_*(5*d)+N*(5*h)+P*(5*u)+L*(5*l)+B*(5*c),O+=D>>>13,D&=8191;let U=O+k*c+C*a+I*i+x*(5*g)+T*(5*f);O=U>>>13,U&=8191,U+=_*(5*p)+N*(5*d)+P*(5*h)+L*(5*u)+B*(5*l),O+=U>>>13,U&=8191;let M=O+k*l+C*c+I*a+x*i+T*(5*g);O=M>>>13,M&=8191,M+=_*(5*f)+N*(5*p)+P*(5*d)+L*(5*h)+B*(5*u),O+=M>>>13,M&=8191;let F=O+k*u+C*l+I*c+x*a+T*i;O=F>>>13,F&=8191,F+=_*(5*g)+N*(5*f)+P*(5*p)+L*(5*d)+B*(5*h),O+=F>>>13,F&=8191;let $=O+k*h+C*u+I*l+x*c+T*a;O=$>>>13,$&=8191,$+=_*i+N*(5*g)+P*(5*f)+L*(5*p)+B*(5*d),O+=$>>>13,$&=8191;let q=O+k*d+C*h+I*u+x*l+T*c;O=q>>>13,q&=8191,q+=_*a+N*i+P*(5*g)+L*(5*f)+B*(5*p),O+=q>>>13,q&=8191;let H=O+k*p+C*d+I*h+x*u+T*l;O=H>>>13,H&=8191,H+=_*c+N*a+P*i+L*(5*g)+B*(5*f),O+=H>>>13,H&=8191;let j=O+k*f+C*p+I*d+x*h+T*u;O=j>>>13,j&=8191,j+=_*l+N*c+P*a+L*i+B*(5*g),O+=j>>>13,j&=8191;let V=O+k*g+C*f+I*p+x*d+T*h;O=V>>>13,V&=8191,V+=_*u+N*l+P*c+L*a+B*i,O+=V>>>13,V&=8191,O=(O<<2)+O|0,O=O+R|0,R=8191&O,O>>>=13,D+=O,o[0]=R,o[1]=D,o[2]=U,o[3]=M,o[4]=F,o[5]=$,o[6]=q,o[7]=H,o[8]=j,o[9]=V}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let 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 o=(1^n)-1;for(let e=0;e<10;e++)r[e]&=o;o=~o;for(let t=0;t<10;t++)e[t]=e[t]&o|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);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;Ph(r)}update(e){Ch(this);const{buffer:t,blockLen:r}=this,n=(e=xh(e)).length;for(let o=0;o<n;){const s=Math.min(r-this.pos,n-o);if(s!==r)t.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-o;o+=r)this.process(e,o)}return this}destroy(){Ph(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ch(this),function(e,t){kh(e);const r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let t=0;t<8;t++)e[o++]=r[t]>>>0,e[o++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const Vh=function(e){const t=(t,r)=>e(r).update(xh(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new jh(e)));function zh(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],l=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=o,w=r[0],v=r[1],E=r[2],S=i,A=a,k=c,C=l,I=u,x=h,T=d,_=p,N=f,P=g,L=m,B=y,O=b,R=w,D=v,U=E;for(let e=0;e<s;e+=2)S=S+I|0,O=Uh(O^S,16),N=N+O|0,I=Uh(I^N,12),S=S+I|0,O=Uh(O^S,8),N=N+O|0,I=Uh(I^N,7),A=A+x|0,R=Uh(R^A,16),P=P+R|0,x=Uh(x^P,12),A=A+x|0,R=Uh(R^A,8),P=P+R|0,x=Uh(x^P,7),k=k+T|0,D=Uh(D^k,16),L=L+D|0,T=Uh(T^L,12),k=k+T|0,D=Uh(D^k,8),L=L+D|0,T=Uh(T^L,7),C=C+_|0,U=Uh(U^C,16),B=B+U|0,_=Uh(_^B,12),C=C+_|0,U=Uh(U^C,8),B=B+U|0,_=Uh(_^B,7),S=S+x|0,U=Uh(U^S,16),L=L+U|0,x=Uh(x^L,12),S=S+x|0,U=Uh(U^S,8),L=L+U|0,x=Uh(x^L,7),A=A+T|0,O=Uh(O^A,16),B=B+O|0,T=Uh(T^B,12),A=A+T|0,O=Uh(O^A,8),B=B+O|0,T=Uh(T^B,7),k=k+_|0,R=Uh(R^k,16),N=N+R|0,_=Uh(_^N,12),k=k+_|0,R=Uh(R^k,8),N=N+R|0,_=Uh(_^N,7),C=C+I|0,D=Uh(D^C,16),P=P+D|0,I=Uh(I^P,12),C=C+I|0,D=Uh(D^C,8),P=P+D|0,I=Uh(I^P,7);let M=0;n[M++]=i+S|0,n[M++]=a+A|0,n[M++]=c+k|0,n[M++]=l+C|0,n[M++]=u+I|0,n[M++]=h+x|0,n[M++]=d+T|0,n[M++]=p+_|0,n[M++]=f+N|0,n[M++]=g+P|0,n[M++]=m+L|0,n[M++]=y+B|0,n[M++]=b+O|0,n[M++]=w+R|0,n[M++]=v+D|0,n[M++]=E+U|0}const Kh=qh(zh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Gh=qh(zh,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let o=e[0],s=e[1],i=e[2],a=e[3],c=t[0],l=t[1],u=t[2],h=t[3],d=t[4],p=t[5],f=t[6],g=t[7],m=r[0],y=r[1],b=r[2],w=r[3];for(let e=0;e<20;e+=2)o=o+c|0,m=Uh(m^o,16),d=d+m|0,c=Uh(c^d,12),o=o+c|0,m=Uh(m^o,8),d=d+m|0,c=Uh(c^d,7),s=s+l|0,y=Uh(y^s,16),p=p+y|0,l=Uh(l^p,12),s=s+l|0,y=Uh(y^s,8),p=p+y|0,l=Uh(l^p,7),i=i+u|0,b=Uh(b^i,16),f=f+b|0,u=Uh(u^f,12),i=i+u|0,b=Uh(b^i,8),f=f+b|0,u=Uh(u^f,7),a=a+h|0,w=Uh(w^a,16),g=g+w|0,h=Uh(h^g,12),a=a+h|0,w=Uh(w^a,8),g=g+w|0,h=Uh(h^g,7),o=o+l|0,w=Uh(w^o,16),f=f+w|0,l=Uh(l^f,12),o=o+l|0,w=Uh(w^o,8),f=f+w|0,l=Uh(l^f,7),s=s+u|0,m=Uh(m^s,16),g=g+m|0,u=Uh(u^g,12),s=s+u|0,m=Uh(m^s,8),g=g+m|0,u=Uh(u^g,7),i=i+h|0,y=Uh(y^i,16),d=d+y|0,h=Uh(h^d,12),i=i+h|0,y=Uh(y^i,8),d=d+y|0,h=Uh(h^d,7),a=a+c|0,b=Uh(b^a,16),p=p+b|0,c=Uh(c^p,12),a=a+c|0,b=Uh(b^a,8),p=p+b|0,c=Uh(c^p,7);let v=0;n[v++]=o,n[v++]=s,n[v++]=i,n[v++]=a,n[v++]=m,n[v++]=y,n[v++]=b,n[v++]=w},allowShortKeys:!1}),Wh=new Uint8Array(16),Jh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(Wh.subarray(r))},Xh=new Uint8Array(32);function Yh(e,t,r,n,o){const s=e(t,r,Xh),i=Vh.create(s);o&&Jh(i,o),Jh(i,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;_h(c,0,BigInt(o?o.length:0),!0),_h(c,8,BigInt(n.length),!0),i.update(a);const u=i.digest();return Ph(s,a),u}const Zh=e=>(t,r,n)=>(kh(t,32),kh(r),{encrypt(o,s){const i=o.length,a=i+16;s?kh(s,a):s=new Uint8Array(a),e(t,r,o,s,1);const c=Yh(e,t,r,s.subarray(0,-16),n);return s.set(c,i),Ph(c),s},decrypt(o,s){const i=o.length,a=i-16;if(i<16)throw new Error("encrypted data must be at least 16 bytes");s?kh(s,a):s=new Uint8Array(a);const c=o.subarray(0,-16),l=o.subarray(-16),u=Yh(e,t,r,c,n);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(l,u))throw new Error("invalid tag");return e(t,r,c,s,1),Ph(u),s}}),Qh=Th({blockSize:64,nonceLength:12,tagLength:16},Zh(Kh));Zh(Gh);const ed=new Uint8Array([0]),td=new Uint8Array;const rd={hashSHA256:e=>jr(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Tr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Au(e,Br(r),Br(t))}(jr,t,e),n=function(e,t,r,n=32){if(Tr(e),Ir(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(n/e.outputLen);void 0===r&&(r=td);const s=new Uint8Array(o*e.outputLen),i=Au.create(e,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let t=0;t<o;t++)ed[0]=t+1,a.update(0===t?td:c).update(r).update(ed).digestInto(c),s.set(c,e.outputLen*t),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),ed.fill(0),s.slice(0,n)}(jr,r,void 0,96);return[n.subarray(0,32),n.subarray(32,64),n.subarray(64,96)]},generateX25519KeyPair(){const e=Za.utils.randomPrivateKey();return{publicKey:Za.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Za.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Za.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>Qh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,o)=>Qh(n,t,r).decrypt(e.subarray(),o)},nd=e=>{const t=m(2);return t[0]=e>>8,t[1]=e,t};nd.bytes=2;const od=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function sd(e,t){t.enabled&&vh&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${Zr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Zr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function id(e,t){t.enabled&&vh&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Zr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Zr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function ad(e,t){t.enabled&&vh&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Zr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function cd(e,t,r){r.enabled&&vh&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&Zr(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Zr(t.k,"hex")}`))}od.bytes=2;class ld extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=ld.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class ud{n;bytes;view;constructor(e=0){this.n=e,this.bytes=g(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 new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const hd=g(0);class dd{k;n;crypto;constructor(e,t=void 0,r=0){this.crypto=e,this.k=t,this.n=new ud(r)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class pd{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=xt(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=g(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new dd(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new dd(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new _n(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,hd);return[new dd(this.crypto,e),new dd(this.crypto,t)]}}class fd{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:o,s,e:i,rs:a,re:c}=e;this.crypto=t,this.ss=new pd(t,r),this.ss.mixHash(n),this.initiator=o,this.s=s,this.e=i,this.rs=a,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw new Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class gd extends fd{writeMessageA(e){return new _n(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new _n(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new _n(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new ld(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new ld(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new ld(`handshake stage 2 validation fail: ${e.message}`)}}}var md,yd;async function bd(e,t,r){const n=await e.sign(vd(t));return yd.encode({identityKey:Wu(e.publicKey),identitySig:n,extensions:r})}async function wd(e,t,r){try{const n=yd.decode(e),o=Gu(n.identityKey);if(!1===r?.equals(o))throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");const s=vd(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(e){throw new Gs(e.message)}}function vd(e){const t=xt("noise-libp2p-static-key:");return e instanceof Uint8Array?kn([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r}))),t),e.encode=t=>qt(t,e.codec()),e.decode=t=>K(t,e.codec())}(md||(md={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),md.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:g(0),identitySig:g(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=md.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>qt(t,e.codec()),e.decode=t=>K(t,e.codec())}(yd||(yd={}));class Ed{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:o,prologueBytes:s}=t,{metrics:i}=e;this.components=e;const a=o??rd;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(a),this.extensions=n,this.metrics=i?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(i):void 0,this.staticKey=r?a.generateX25519KeyPairFromSeed(r):a.generateX25519KeyPair(),this.prologue=s??g(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ju]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=yh(e,{lengthEncoder:nd,lengthDecoder:od,maxDataLength:wh}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(r,n);e.source=o.source,e.sink=o.sink;const s=Gu(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:oh(s)}}async secureInbound(e,t){const r=yh(e,{lengthEncoder:nd,lengthDecoder:od,maxDataLength:wh}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(r,n);e.source=o.source,e.sink=o.sink;const s=Gu(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:oh(s)}}async performHandshakeInitiator(e,t,r,n){let o;try{o=await async function(e,t){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await bd(s,a.publicKey,l),h=new gd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});sd(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(hd),t),r.trace("Stage 0 - Initiator finished sending first message."),id(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),ad(h.re,r),p=h.rs,(f=r).enabled&&vh&&f(p?`REMOTE_STATIC_PUBLIC_KEY ${Zr(p.subarray(),"hex")}`:"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await wd(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return cd(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd(hd,e),decrypt:(e,t)=>y.decryptWithAd(hd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return o}async performHandshakeResponder(e,t,r,n){let o;try{o=await async function(e,t){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await bd(s,a.publicKey,l),h=new gd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});sd(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),ad(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),id(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await wd(d,h.rs,c),[f,g]=h.ss.split();return cd(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(hd,e),decrypt:(e,t)=>f.decryptWithAd(hd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return o}async createSecureConnection(e,t){const[r,n]=function(){const e=bh(),t=bh();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),o=e.unwrap();return await Kn(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let o,s=r+65519;s>n.length&&(s=n.length),o=n instanceof Uint8Array?e.encrypt(n.subarray(r,s)):e.encrypt(n.sublist(r,s)),t?.encryptedPackets.increment(),yield new _n(nd(o.byteLength),o)}}}(t,this.metrics),o,(e=>Fn(e,{lengthDecoder:od})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=wh){let o=r+wh;if(o>n.length&&(o=n.length),o-16<r)throw new Error("Invalid chunk");const s=n.sublist(r,o),i=n.subarray(r,o-16);try{const r=e.decrypt(s,i);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}}function Sd(e={}){return t=>new Ed(t,e)}const Ad=Symbol.for("@libp2p/peer-discovery"),kd=tp("dns4"),Cd=tp("dns6"),Id=tp("dnsaddr"),xd=ep(tp("dns"),Id,kd,Cd),Td=ep(tp("ip4"),tp("ip6")),_d=ep(Qd(Td,tp("tcp")),Qd(xd,tp("tcp"))),Nd=Qd(Td,tp("udp")),Pd=Qd(Nd,tp("utp")),Ld=Qd(Nd,tp("quic")),Bd=Qd(Nd,tp("quic-v1")),Od=ep(Qd(_d,tp("ws")),Qd(xd,tp("ws"))),Rd=ep(Qd(Od,tp("p2p")),Od),Dd=ep(Qd(_d,tp("wss")),Qd(xd,tp("wss")),Qd(_d,tp("tls"),tp("ws")),Qd(xd,tp("tls"),tp("ws"))),Ud=ep(Qd(Dd,tp("p2p")),Dd),Md=ep(Qd(_d,tp("http")),Qd(Td,tp("http")),Qd(xd,tp("http"))),Fd=ep(Qd(_d,tp("https")),Qd(Td,tp("https")),Qd(xd,tp("https"))),$d=Qd(Nd,tp("webrtc-direct"),tp("certhash")),qd=ep(Qd($d,tp("p2p")),$d),Hd=Qd(Bd,tp("webtransport"),tp("certhash"),tp("certhash")),jd=ep(Qd(Hd,tp("p2p")),Hd),Vd=ep(Qd(Rd,tp("p2p-webrtc-star"),tp("p2p")),Qd(Ud,tp("p2p-webrtc-star"),tp("p2p")),Qd(Rd,tp("p2p-webrtc-star")),Qd(Ud,tp("p2p-webrtc-star"))),zd=(ep(Qd(Rd,tp("p2p-websocket-star"),tp("p2p")),Qd(Ud,tp("p2p-websocket-star"),tp("p2p")),Qd(Rd,tp("p2p-websocket-star")),Qd(Ud,tp("p2p-websocket-star"))),ep(Qd(Md,tp("p2p-webrtc-direct"),tp("p2p")),Qd(Fd,tp("p2p-webrtc-direct"),tp("p2p")),Qd(Md,tp("p2p-webrtc-direct")),Qd(Fd,tp("p2p-webrtc-direct")))),Kd=ep(Od,Dd,Md,Fd,Vd,zd,_d,Pd,Ld,xd,qd,jd),Gd=(ep(Qd(Kd,tp("p2p-stardust"),tp("p2p")),Qd(Kd,tp("p2p-stardust"))),ep(Qd(Kd,tp("p2p")),Vd,zd,qd,jd,tp("p2p"))),Wd=ep(Qd(Gd,tp("p2p-circuit"),Gd),Qd(Gd,tp("p2p-circuit")),Qd(tp("p2p-circuit"),Gd),Qd(Kd,tp("p2p-circuit")),Qd(tp("p2p-circuit"),Kd),tp("p2p-circuit")),Jd=()=>ep(Qd(Wd,Jd),Wd),Xd=Jd(),Yd=ep(Qd(Xd,Gd,Xd),Qd(Gd,Xd),Qd(Xd,Gd),Xd,Gd);function Zd(e){return function(t){let r;try{r=Is(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Qd(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Zd(t),partialMatch:t}}function ep(...e){function t(t){let r=null;return e.some((e=>{const 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:Zd(t),partialMatch:t}}function tp(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=Is(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}ep(Qd(Xd,tp("webrtc"),tp("p2p")),Qd(Xd,tp("webrtc")),Qd(Kd,tp("webrtc"),tp("p2p")),Qd(Kd,tp("webrtc")),tp("webrtc"));class rp extends xo{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!Yd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=Is(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:nh(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[Ad]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Ju]=["@libp2p/peer-discovery"];isStarted(){return Boolean(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(const 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}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch((t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}const np=Uint8Array.from([3,1]);var op,sp;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=vr(((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,r={})=>{const n={multiaddr:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();t>>>3==1?n.multiaddr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const o={peerId:g(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:o.peerId=t.bytes();break;case 2:o.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&o.addresses.length===n.limits.addresses)throw new Er('Decode error - map field "addresses" had too many elements');o.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return o}))),r),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(op||(op={}));class ip{static createFromProtobuf=e=>{const t=op.decode(e),r=sh(st(t.peerId)),n=(t.addresses??[]).map((e=>Is(e.multiaddr))),o=t.seq;return new ip({peerId:r,multiaddrs:n,seqNumber:o})};static DOMAIN="libp2p-peer-record";static CODEC=np;peerId;multiaddrs;seqNumber;domain=ip.DOMAIN;codec=ip.CODEC;marshaled;constructor(e){const{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=op.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof ip&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const 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)}}!function(e){let t;e.codec=()=>(null==t&&(t=vr(((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,r={})=>{const n={publicKey:g(0),payloadType:g(0),payload:g(0),signature:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.publicKey=e.bytes();break;case 2:n.payloadType=e.bytes();break;case 3:n.payload=e.bytes();break;case 5:n.signature=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(sp||(sp={}));class ap extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class cp{static createFromProtobuf=async e=>{const t=sp.decode(e),r=Gu(t.publicKey);return new cp({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t)throw new Error("Missing private key");const r=e.domain,n=e.codec,o=e.marshal(),s=lp(r,n,o),i=await t.sign(s.subarray());return new cp({publicKey:t.publicKey,payloadType:n,payload:o,signature:i})};static openAndCertify=async(e,t)=>{const r=await cp.createFromProtobuf(e);if(!await r.validate(t))throw new ap("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:o}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=o}marshal(){return null==this.marshaled&&(this.marshaled=sp.encode({publicKey:Wu(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Cn(this.marshal(),e.marshal())}async validate(e){const t=lp(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}}const lp=(e,t,r)=>{const n=xt(e),o=_(n.byteLength),s=_(t.length),i=_(r.length);return new _n(o,n,s,t,i,r)};var up=__webpack_require__(5507);const hp=["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 up.Netmask(e)));function dp(e){for(const t of hp)if(t.contains(e))return!0;return!1}function pp(e){return Jo(e)?dp(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return dp(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return dp(t[t.length-1])}(e):Xo(e)?function(e){return/^::$/.test(e)||/^::1$/.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)}(e):void 0}function fp(e){try{const[[t,r]]=e.stringTuples();if(null==r)return!0;if(53===t||54===t||55===t||56===t)return!1;if(4===t||41===t)return pp(r)??!1}catch{}return!0}const gp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),mp=e=>({match:t=>gp((t=>t===e)).match(t),pattern:e}),yp=()=>({match:e=>gp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),bp=()=>({match:e=>gp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),wp=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{Se.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),vp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{Ie.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Ep=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),Sp=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),Ap=(...e)=>({match:t=>{for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function kp(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const Cp=Ap(mp("dns4"),yp()),Ip=Ap(mp("dns6"),yp()),xp=Ap(mp("dnsaddr"),yp()),Tp=Ap(mp("dns"),yp()),_p=(kp(Cp,Ep(wp())),kp(Ip,Ep(wp())),kp(xp,Ep(wp())),kp(Sp(Tp,xp,Cp,Ip),Ep(wp())),Ap(mp("ip4"),gp(Jo))),Np=Ap(mp("ip6"),gp(Xo)),Pp=Sp(_p,Np),Lp=Sp(Pp,Tp,Cp,Ip,xp),Bp=kp(Sp(Pp,Ap(Sp(Tp,xp,Cp,Ip),Ep(wp())))),Op=(kp(_p),kp(Np),kp(Pp),Ap(Lp,mp("tcp"),bp())),Rp=Ap(Lp,mp("udp"),bp()),Dp=kp(Ap(Op,Ep(wp()))),Up=(kp(Rp),Ap(Rp,mp("quic"),Ep(wp()))),Mp=Ap(Rp,mp("quic-v1"),Ep(wp())),Fp=Sp(Up,Mp),$p=(kp(Up),kp(Mp),Sp(Lp,Op,Rp,Up,Mp)),qp=Sp(Ap($p,mp("ws"),Ep(wp()))),Hp=kp(qp),jp=Sp(Ap($p,mp("wss"),Ep(wp())),Ap($p,mp("tls"),Ep(Ap(mp("sni"),yp())),mp("ws"),Ep(wp()))),Vp=kp(jp),zp=Ap(Rp,mp("webrtc-direct"),Ep(vp()),Ep(vp()),Ep(wp())),Kp=kp(zp),Gp=Ap(Mp,mp("webtransport"),Ep(vp()),Ep(vp()),Ep(wp())),Wp=kp(Gp),Jp=Sp(qp,jp,Ap(Op,Ep(wp())),Ap(Fp,Ep(wp())),Ap(Lp,Ep(wp())),zp,Gp,wp()),Xp=(kp(Jp),kp(Ap(Jp,mp("p2p-circuit"),wp()))),Yp=kp(Sp(Ap(Jp,mp("p2p-circuit"),mp("webrtc"),Ep(wp())),Ap(Jp,mp("webrtc"),Ep(wp())),Ap(mp("webrtc"),Ep(wp()))));function Zp(e,t){const r=yh(e,t),n={read:async(e,t)=>{const 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}var Qp;kp(Sp(Ap(Lp,mp("tcp"),bp(),mp("http"),Ep(wp())),Ap(Lp,mp("http"),Ep(wp())))),kp(Sp(Ap(Lp,mp("tcp"),Sp(Ap(mp("443"),mp("http")),Ap(bp(),mp("https"))),Ep(wp())),Ap(Lp,mp("tls"),mp("http"),Ep(wp())),Ap(Lp,mp("https"),Ep(wp())))),kp(Sp(Ap(mp("memory"),yp(),Ep(wp())))),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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(const 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(const 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,r={})=>{const n={listenAddrs:[],protocols:[]},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new Er('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new Er('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Qp||(Qp={}));var ef=__webpack_require__(4866);const tf="object"==typeof window&&"object"==typeof document&&9===document.nodeType,rf=ef(),nf=tf&&!rf,of=rf&&!tf,sf=rf&&tf,af=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!rf,cf="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,lf=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product),uf="ipfs",hf=5e3,df=1,pf=1,ff=10,gf=8192,mf=!0,yf=!0;class bf{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??hf,this.maxInboundStreams=t.maxInboundStreams??df,this.maxOutboundStreams=t.maxOutboundStreams??pf,this.maxMessageSize=t.maxMessageSize??gf,this.maxObservedAddresses=t.maxObservedAddresses??ff,this.runOnLimitedConnection=t.runOnLimitedConnection??yf,this.host={protocolVersion:`${t.protocolPrefix??uf}/0.1.0`,agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n||(n=`${r.name}/${r.version}`,af||of?n+=` UserAgent=${globalThis.process.version}`:(nf||cf||sf||lf)&&(n+=` UserAgent=${globalThis.navigator.userAgent}`)),n)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:xt(this.host.agentVersion),ProtocolVersion:xt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class wf extends bf{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??uf}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??mf)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==ci.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}[Ju]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Zp(r,{maxDataLength:this.maxMessageSize}).pb(Qp),o=await n.read(t);return await r.close(t),o}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:o,observedAddr:s}=r;if(null==n)throw new li("public key was missing from identify message");const i=ih(Gu(n).toCID());if(!e.remotePeer.equals(i))throw new li("identified peer does not match the expected peer");if(this.peerId.equals(i))throw new li("identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("identify completed for peer %p and protocols %o",i,o),async function(e,t,r,n,o){if(r("received identify from %p",n.remotePeer),null==o)throw new li("message was null or undefined");const s={};if(o.listenAddrs.length>0&&(s.addresses=o.listenAddrs.map((e=>({isCertified:!1,multiaddr:Is(e)})))),o.protocols.length>0&&(s.protocols=o.protocols),null!=o.publicKey){const e=Gu(o.publicKey);if(!oh(e).equals(n.remotePeer))throw new li("public key did not match remote PeerId");s.publicKey=e}let i;if(null!=o.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=o.signedPeerRecord;const a=await cp.openAndCertify(t,ip.DOMAIN);let c=ip.createFromProtobuf(a.payload);const l=ih(a.publicKey.toCID());if(!c.peerId.equals(l))throw new li("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new li("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(s.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=await cp.createFromProtobuf(u.peerRecordEnvelope),n=ip.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}s.peerRecordEnvelope=t,s.addresses=c.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),i={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,s),await e.patch(n.remotePeer,s),null!=o.agentVersion||null!=o.protocolVersion){const t={};null!=o.agentVersion&&(t.AgentVersion=xt(o.agentVersion)),null!=o.protocolVersion&&(t.ProtocolVersion=xt(o.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:o.protocolVersion,agentVersion:o.agentVersion,publicKey:o.publicKey,listenAddrs:o.listenAddrs.map((e=>Is(e))),observedAddr:null==o.observedAddr?void 0:Is(o.observedAddr),protocols:o.protocols,signedPeerRecord:i,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Is(e)}catch{}}(e);null!=t&&(this.log.trace("our observed address was %a",t),fp(t)?this.log.trace("our observed address was private"):41!==t.stringTuples()[0][0]||function(e){try{const[[r,n]]=e.stringTuples();if(null==n)return!1;if(41===r)return t=n,new Wo("2000::/3").contains(t)}catch{}var t;return!1}(t)?Dp.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address"))}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),o=this.addressManager.getAddresses().map((e=>e.decapsulateCode(os("p2p").code)));let s=e.peerRecordEnvelope;if(o.length>0&&null==s){const e=new ip({peerId:this.peerId,multiaddrs:o});s=(await cp.seal(e,this.privateKey)).marshal().subarray()}let i=t.remoteAddr.bytes;Bp.matches(t.remoteAddr)||(i=void 0);const a=Zp(r).pb(Qp);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Wu(this.privateKey.publicKey),listenAddrs:o.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:i,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function vf(e={}){return t=>new wf(t,e)}function Ef(e,t){const 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 new Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Sf=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},Af=new WeakMap,kf=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Sf());let s,i,a;const c=e??clearTimeout,l=()=>{c(s),a(Sf())},u=new Promise(((e,c)=>{i=()=>{o&&o.removeEventListener("abort",l),e(n)},a=c,s=(t??setTimeout)(i,r)}));return o&&o.addEventListener("abort",l,{once:!0}),Af.set(u,(()=>{c(s),s=null,i()})),u}}();class Cf extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}class If extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class xf{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 Tf}async consume(e,t=1,r={}){const n=this.getKey(e),o=this._getKeySecDuration(r);let s=this.memoryStorage.incrby(n,t,o);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 Cf("Rate limit exceeded",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let e=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=s.consumedPoints*this.execEvenlyMinDelayMs),await kf(e)}return s}penalty(e,t=1,r={}){const n=this.getKey(e),o=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,t,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,r={}){const n=this.getKey(e),o=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,-t,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const 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 null!=e?.customDuration&&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 Tf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const o=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||o>0?(n.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,o=this.storage.get(e);null!=o&&clearTimeout(o.timeoutId);const 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){const 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){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var _f;!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(_f||(_f={}));const Nf=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Pf=Object.freeze({NEW_STREAM:_f.NEW_STREAM,MESSAGE:_f.MESSAGE_INITIATOR,CLOSE:_f.CLOSE_INITIATOR,RESET:_f.RESET_INITIATOR}),Lf=Object.freeze({MESSAGE:_f.MESSAGE_RECEIVER,CLOSE:_f.CLOSE_RECEIVER,RESET:_f.RESET_RECEIVER}),Bf=1<<20;class Of{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Bf,t=4194304){this._buffer=new _n,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 new li("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:e,type:r,length:n,offset:o}=this._headerInfo;if(this._buffer.length-o<n)break;const s={id:e,type:r};r!==_f.NEW_STREAM&&r!==_f.MESSAGE_INITIATOR&&r!==_f.MESSAGE_RECEIVER||(s.data=this._buffer.sublist(o,o+n)),t.push(s),this._buffer.consume(o+n),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=Uf(e),{value:n,offset:o}=Uf(e,r),s=7&t;if(null==Nf[s])throw new Error(`Invalid type received: ${s}`);if(n>this._maxMessageSize)throw new li("Message size too large");return{id:t>>3,type:s,offset:r+o,length:n}}}const Rf=128,Df=127;function Uf(e,t=0){let r,n=0,o=0,s=t;const i=e.length;do{if(s>=i||o>49)throw t=0,new RangeError("Could not decode varint");r=e.get(s++),n+=o<28?(r&Df)<<o:(r&Df)*Math.pow(2,o),o+=7}while(r>=Rf);return{value:n,offset:t=s-t}}const Mf=10240,Ff=new class{_pool;_poolOffset;constructor(){this._pool=m(Mf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;_(e.id<<3|e.type,r,n),n+=I(e.id<<3|e.type),e.type!==_f.NEW_STREAM&&e.type!==_f.MESSAGE_INITIATOR&&e.type!==_f.MESSAGE_RECEIVER||null==e.data?(_(0,r,n),n+=I(0)):(_(e.data.length,r,n),n+=I(e.data.length));const o=r.subarray(this._poolOffset,n);Mf-n<100?(this._pool=m(Mf),this._poolOffset=0):this._poolOffset=n,t.append(o),e.type!==_f.NEW_STREAM&&e.type!==_f.MESSAGE_INITIATOR&&e.type!==_f.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class $f extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function qf(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Hf{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=$n(),this.closed=$n(),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=Vn({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 ri(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);qf(e)&&await e}const r=()=>{Ef(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new _n(r):r;const e=this.sendData(r,t);qf(e)&&(this.sendingData=$n(),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){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await ch(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);const 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 ch(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await ch(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ch(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");const t=this.sendReset();qf(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;const e=new ti("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(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class jf extends Hf{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?Pf:Lf,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:Pf.NEW_STREAM,data:new _n(xt(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const 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 Vf(e){const t={...e,type:`${Nf[e.type]} (${e.type})`};return e.type===_f.NEW_STREAM&&(t.data=Zr(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==_f.MESSAGE_INITIATOR&&e.type!==_f.MESSAGE_RECEIVER||(t.data=Zr(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class zf{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=Vn({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=Kn(this._source,(e=>async function*(e){for await(const t of e){const e=new _n;Ff.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new xf({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new ei("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const 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){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:o}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new mi("Too many outbound streams open");if(o.has(t))throw new Error(`${n} stream ${t} already exists!`);const s=function(e){const{id:t,name:r,send:n,onEnd:o,type:s="initiator",maxMsgSize:i=Bf}=e;return new jf({id:"initiator"===s?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:"initiator"===s?"outbound":"inbound",maxDataSize:i,onEnd:o,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${s}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,Vf(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,s.protocol),o.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(s)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return o.set(t,s),s}_createSink(){return async e=>{const t=()=>{Ef(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Of(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const 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){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",Vf(e)),e.type===_f.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:_f.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(new Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:Zr(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,Nf[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(new Error("Too many messages for missing streams"))}return}const o=this._init.maxStreamBufferSize??4194304;try{switch(r){case _f.MESSAGE_INITIATOR:case _f.MESSAGE_RECEIVER:if(n.sourceReadableLength()>o)throw this._source.push({id:e.id,type:r===_f.MESSAGE_INITIATOR?_f.RESET_RECEIVER:_f.RESET_INITIATOR}),new $f("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case _f.CLOSE_INITIATOR:case _f.CLOSE_RECEIVER:n.remoteCloseWrite();break;case _f.RESET_INITIATOR:case _f.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 Kf{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[Ju]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new zf(this.components,{...e,...this._init})}}function Gf(e={}){return t=>new Kf(t,e)}function Wf(e){if(isNaN(e)||e<=0)throw new Ws("random bytes length must be a Number bigger than 0");return Dr(e)}class Jf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;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.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),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);const{stream:t}=e,r=Date.now();AbortSignal.timeout(this.timeout).addEventListener("abort",(()=>{t?.abort(new hi("ping timeout"))})),Kn(t,(async function*(e){let r=0;for await(const n of e){if(r+=n.byteLength,r>32)return void t?.abort(new li("Too much data received"));yield n}}),t).catch((r=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,r),t?.abort(r)})).finally((()=>{const t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=Wf(32),o=await this.components.connectionManager.openConnection(e,t);let s,i=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{s=await o.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),i=()=>{s?.abort(new Ks)},t.signal?.addEventListener("abort",i,{once:!0});const e=await Kn([n],s,(async e=>function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e)return t})();for(const t of e)return t}(e))),a=Date.now()-r;if(null==e)throw new ui(`Did not receive a ping ack after ${a}ms`);if(!Cn(n,e.subarray()))throw new ui(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",o.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",o.remotePeer,e),s?.abort(e),e}finally{t.signal?.removeEventListener("abort",i),null!=s&&await s.close()}}}function Xf(e={}){return t=>new Jf(t,e)}const Yf=Symbol.for("@libp2p/transport");var Zf;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Zf||(Zf={}));const Qf=[os("tcp").code,os("dns").code,os("dnsaddr").code,os("dns4").code,os("dns6").code];function eg(e){return rg("sni",e)?.[1]}function tg(e){const t=rg("tcp",e)?.[1];return null==t?"":`:${t}`}function rg(e,t){let r;try{r=os(e).code}catch(e){return}for(const[e,n]of t)if(e===r&&null!=n)return[e,n]}function ng(e){return e.some((([e,t])=>e===os("tls").code))}function og(e,t,r){const n=sg[os(e).name];if(null==n)throw new Error(`Can't interpret protocol ${os(e).name}`);const o=n(t,r);return e===os("ip6").code?`[${o}]`:o}const sg={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`tcp://${og(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`udp://${og(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)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${og(r[0],r[1]??"",t)}`},p2p:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${og(r[0],r[1]??"",t)}`},http:(e,t)=>{const r=ng(t),n=eg(t),o=tg(t);if(r&&null!=n)return`https://${n}${o}`;const s=r?"https://":"http://",i=t.pop();if(null==i)throw new Error("Unexpected end of multiaddr");let a=og(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${s}${a}`},"http-path":(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${og(r[0],r[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return og(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return og(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");let n=og(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=ng(t),n=eg(t),o=tg(t);if(r&&null!=n)return`wss://${n}${o}`;const s=r?"wss://":"ws://",i=t.pop();if(null==i)throw new Error("Unexpected end of multiaddr");let a=og(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${s}${a}`},wss:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");let n=og(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}},ig=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",o),e.removeEventListener("error",s)}function o(){n(),t()}function s(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",o),e.addEventListener("error",s)}))},ag=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await ig(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=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(new Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))});var cg=__webpack_require__(544);function lg(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const ug=WebSocket,hg={"http:":"ws:","https:":"wss:"};function dg(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,o=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${o}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(hg))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(o)return void t();if(null!=n)return void r(n);const s=t=>{e.removeEventListener("open",i),e.removeEventListener("error",a),t()},i=()=>{s(t)},a=t=>{s((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",i),e.addEventListener("error",a)}))},r=async function*(){const r=new cg.PP((({push:t,stop:r,fail:n})=>{const o=e=>{let r=null;"string"==typeof e.data&&(r=xt(e.data)),lg(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},s=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",o),e.addEventListener("error",s),e.addEventListener("close",r),()=>{e.removeEventListener("message",o),e.removeEventListener("error",s),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield lg(e)?new Uint8Array(e):e}();let n,o=1===e.readyState;return e.addEventListener("open",(()=>{o=!0,n=null})),e.addEventListener("close",(()=>{o=!1,n=null})),e.addEventListener("error",(t=>{o||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,o=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,o=parseInt(t.port,10)}catch{}if(null==n||null==o)throw new Error("Remote connection did not have address and/or port");return{sink:ag(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:o,socket:e}})(new ug(r.toString(),t.websocket),t)}class pg extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function fg(e){return e.filter((e=>Vp.exactMatch(e)||Hp.exactMatch(e)))}function gg(e){return e.filter((e=>Vp.exactMatch(e)))}class mg{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Yf]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ju]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),o=r.metrics,s=r.metricPrefix??"",i={log:n,async sink(t){try{await e.sink(async function*(){for await(const 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={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const o=()=>{const{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 Ks("Socket close timeout"))};t.signal?.addEventListener("abort",o);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",o),i.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),i.timeline.close=Date.now(),o?.increment({[`${s}error`]:!0})}};return e.socket.addEventListener("close",(()=>{o?.increment({[`${s}close`]:!0}),null==i.timeline.close&&(i.timeline.close=Date.now())}),{once:!0}),i}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=$n(),o=dg(function(e){const t=Is(e).stringTuples(),r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");const n=os(r[0]),o=sg[n.name];if(null==o)throw new Error(`No interpreter found for ${n.name}`);let s=o(r[1]??"",t);return Qf.includes(r[0])&&(s=s.replace(/^.*:\/\//,""),s="443"===r[1]?`https://${s}`:`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);o.socket.addEventListener("error",(()=>{const t=new Qs(`Could not connect to ${e.toString()}`);this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new pg("websockets:open-connection")),await ch(Promise.race([o.connected(),n.promise]),t.signal)}catch(e){throw!0===t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),o.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):fg(e)}dialFilter(e){return this.listenFilter(e)}}function yg(e={}){return t=>new mg(t,e)}var bg=__webpack_require__(228);class wg extends Error{constructor(e){super(e),this.name="TimeoutError"}}class vg extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const Eg=e=>void 0===globalThis.DOMException?new vg(e):new DOMException(e),Sg=e=>{const t=void 0===e.reason?Eg("This operation was aborted."):e.reason;return t instanceof Error?t:Eg(t)};function Ag(e,t){const{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t;let i,a;const c=new Promise(((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(Sg(e)),a=()=>{l(Sg(e))},e.addEventListener("abort",a,{once:!0})}if(r===Number.POSITIVE_INFINITY)return void e.then(c,l);const u=new wg;i=s.setTimeout.call(void 0,(()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===o?c():o instanceof Error?l(o):(u.message=o??`Promise timed out after ${r} milliseconds`,l(u))}),r),(async()=>{try{c(await e)}catch(e){l(e)}})()})).finally((()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}class kg{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t){let r=0,n=e.length;for(;n>0;){const s=Math.trunc(n/2);let i=r+s;o=e[i],t.priority-o.priority<=0?(r=++i,n-=s+1):n=s}var o;return r}(this.#s,r);this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){const e=this.#s.shift();return e?.run}filter(e){return this.#s.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#s.length}}class Cg extends bg{#i;#a;#c=0;#l;#u;#h=0;#d;#p;#s;#f;#g=0;#m;#y;#b;#w=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:kg,...e}).intervalCap&&e.intervalCap>=1))throw new 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 new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#a=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#l=e.intervalCap,this.#u=e.interval,this.#s=new e.queueClass,this.#f=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#b=!0===e.throwOnTimeout,this.#y=!1===e.autoStart}get#v(){return this.#a||this.#c<this.#l}get#E(){return this.#g<this.#m}#S(){this.#g--,this.#A(),this.emit("next")}#k(){this.#C(),this.#I(),this.#p=void 0}get#x(){const e=Date.now();if(void 0===this.#d){const t=this.#h-e;if(!(t<0))return void 0===this.#p&&(this.#p=setTimeout((()=>{this.#k()}),t)),!0;this.#c=this.#i?this.#g:0}return!1}#A(){if(0===this.#s.size)return this.#d&&clearInterval(this.#d),this.#d=void 0,this.emit("empty"),0===this.#g&&this.emit("idle"),!1;if(!this.#y){const e=!this.#x;if(this.#v&&this.#E){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#I(),!0)}}return!1}#I(){this.#a||void 0!==this.#d||(this.#d=setInterval((()=>{this.#C()}),this.#u),this.#h=Date.now()+this.#u)}#C(){0===this.#c&&0===this.#g&&this.#d&&(clearInterval(this.#d),this.#d=void 0),this.#c=this.#i?this.#g:0,this.#T()}#T(){for(;this.#A(););}get concurrency(){return this.#m}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#m=e,this.#T()}async#_(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#w++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#b,...t},new Promise(((r,n)=>{this.#s.enqueue((async()=>{this.#g++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Ag(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#_(t.signal)]));const o=await n;r(o),this.emit("completed",o)}catch(e){if(e instanceof wg&&!t.throwOnTimeout)return void r();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.#y?(this.#y=!1,this.#T(),this):this}pause(){this.#y=!0}clear(){this.#s=new this.#f}async onEmpty(){0!==this.#s.size&&await this.#N("empty")}async onSizeLessThan(e){this.#s.size<e||await this.#N("next",(()=>this.#s.size<e))}async onIdle(){0===this.#g&&0===this.#s.size||await this.#N("idle")}async#N(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#y}}function Ig(e){const t=[_g.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function xg(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:_g[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:_g[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?Zr(e.data):e.data})))}}function Tg(e,t={}){const r=new Cg({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const o=new URLSearchParams;o.set("name",t),Ig(n.types).forEach((e=>{o.append("type",_g[e])})),n.onProgress?.(new pg("dns:query",{detail:t}));const s=await r.add((async()=>{const t=await fetch(`${e}?${o}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=xg(await t.json());return n.onProgress?.(new pg("dns:response",{detail:r})),r}),{signal:n.signal});if(null==s)throw new Error("No DNS response received");return s}}var _g,Ng=__webpack_require__(194);class Pg{lru;constructor(e){this.lru=Ng(e)}get(e,t){let r=!0;const n=[];for(const o of t){const t=this.getAnswers(e,o);if(0===t.length){r=!1;break}n.push(...t)}if(r)return xg({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:_g[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class Lg{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new Pg(t)),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["."]=[Tg("https://cloudflare-dns.com/dns-query"),Tg("https://dns.google/resolve")])}async query(e,t={}){const r=Ig(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new pg("dns:cache",{detail:n})),n;const o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),i=[];for(const n of s){if(!0===t.signal?.aborted)break;try{const o=await n(e,{...t,types:r});for(const t of o.Answer)this.cache.add(e,t);return o}catch(e){i.push(e),t.onProgress?.(new pg("dns:error",{detail:e}))}}if(1===i.length)throw i[0];throw new AggregateError(i,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(_g||(_g={}));const{code:Bg}=os("dnsaddr");class Og extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const Rg=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Og("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===Bg))??[],o=t?.dns??function(e={}){return new Lg(e)}(),s=await o.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[_g.TXT]}),i=e.getPeerId(),a=[];for(const e of s.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=i&&!n.includes(i))continue;const o=Is(n);if(n.startsWith("/dnsaddr")){const e=await o.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(o.toString())}return a},Dg=__webpack_require__(6864),Ug={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:Rg}},transportManager:{faultTolerance:Zf.FATAL_ALL}};async function Mg(e){const t=Dg(Ug,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ws("Private network is enforced, but no protector was provided");return t}const Fg=Symbol.for("@libp2p/content-routing"),$g=Symbol.for("@libp2p/peer-routing"),qg=1e3,Hg=60*qg,jg=60*Hg,Vg=24*jg,zg=7*Vg,Kg=function(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e=String(e)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const 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)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*zg;case"days":case"day":case"d":return r*Vg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*jg;case"minutes":case"minute":case"mins":case"min":case"m":return r*Hg;case"seconds":case"second":case"secs":case"sec":case"s":return r*qg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=Vg?Gg(e,t,Vg,"day"):t>=jg?Gg(e,t,jg,"hour"):t>=Hg?Gg(e,t,Hg,"minute"):t>=qg?Gg(e,t,qg,"second"):`${e} ms`}(e):function(e){const t=Math.abs(e);return t>=Vg?`${Math.round(e/Vg)}d`:t>=jg?`${Math.round(e/jg)}h`:t>=Hg?`${Math.round(e/Hg)}m`:t>=qg?`${Math.round(e/qg)}s`:`${e}ms`}(e);throw new Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw new Error(r)}};function Gg(e,t,r,n){const o=t>=1.5*r;return`${Math.round(e/r)} ${n}${o?"s":""}`}const Wg=function(){try{return localStorage}catch(e){}}(),Jg=console.debug??console.log??(()=>{}),Xg=function(e){function t(e){let n,o,s,i=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),s=o-(n||o);r.diff=s,r.prev=n,r.curr=o,n=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,o)=>{if("%%"===n)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];n=s.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(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(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Kg,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs:function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Kg(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save:function(e){try{e?Wg?.setItem("debug",e):Wg?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=Wg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},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"],storage:Wg,log:Jg}),Yg=Xg;function Zg(){return{forComponent:e=>function(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return Yg.enabled(`${e}:trace`)&&null!=Yg.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Yg(`${e}:trace`)),Object.assign(Yg(e),{error:Yg(`${e}:error`),trace:t})}(e)}}function Qg(e){if(null!=e&&0!==(e=e.trim()).length)return e}function em(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function tm(e){return sh(st(Se.decode(`z${e}`)))}Yg.formatters.b=e=>null==e?"undefined":Se.baseEncode(e),Yg.formatters.t=e=>null==e?"undefined":he.baseEncode(e),Yg.formatters.m=e=>null==e?"undefined":ke.baseEncode(e),Yg.formatters.p=e=>null==e?"undefined":e.toString(),Yg.formatters.c=e=>null==e?"undefined":e.toString(),Yg.formatters.k=e=>null==e?"undefined":e.toString(),Yg.formatters.a=e=>null==e?"undefined":e.toString(),Yg.formatters.e=e=>null==e?"undefined":Qg(e.stack)??Qg(e.message)??e.toString();class rm{set;constructor(e){if(this.set=new Set,null!=e)for(const 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 em(this.set.entries(),(e=>{const t=tm(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=tm(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return em(this.set.values(),(e=>tm(e)))}intersection(e){const t=new rm;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new rm;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new rm;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}const nm={},om=e=>{e.addEventListener("message",(t=>{om.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{om.dispatchEvent("message",e,t)}))};om.addEventListener=(e,t)=>{null==nm[e]&&(nm[e]=[]),nm[e].push(t)},om.removeEventListener=(e,t)=>{null!=nm[e]&&(nm[e]=nm[e].filter((e=>e===t)))},om.dispatchEvent=function(e,t,r){null!=nm[e]&&nm[e].forEach((e=>e(t,r)))};const sm=om,im="lock:worker:request-read",am="lock:worker:release-read",cm="lock:master:grant-read",lm="lock:worker:request-write",um="lock:worker:release-write",hm="lock:master:grant-write",dm=(e,t,r,n,o)=>(s,i)=>{if(i.data.type!==r)return;const a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise((e=>{const t=r=>{if(null==r?.data)return;const o=r.data.type,i=(r.data.name,r.data.identifier);o===n&&i===a.identifier&&(s.removeEventListener("message",t),e())};s.addEventListener("message",t)}))}}}))},pm=(e,t,r,n)=>async()=>{const o=Math.random().toString().substring(2);return globalThis.postMessage({type:t,identifier:o,name:e}),new Promise((t=>{const s=i=>{if(null==i?.data)return;const a=i.data.type,c=i.data.identifier;a===r&&c===o&&(globalThis.removeEventListener("message",s),t((()=>{globalThis.postMessage({type:n,identifier:o,name:e})})))};globalThis.addEventListener("message",s)}))},fm={singleProcess:!1},gm={};let mm;async function ym(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Ag((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const bm={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};var wm,vm,Em;function Sm(e,t){const r=wm.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=oh(Gu(r.publicKey)));const n=new Map,o=BigInt(Date.now());for(const[e,t]of r.tags.entries())null!=t.expiry&&t.expiry<o||n.set(e,t);return{...r,id:e,addresses:r.addresses.map((({multiaddr:e,isCertified:t})=>({multiaddr:Is(e),isCertified:t??!1}))),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}!function(e){let t,r,n;!function(e){let t;e.codec=()=>(null==t&&(t=vr(((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,r={})=>{const n={key:"",value:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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),Em.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=Em.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),vm.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,o]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:o},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,o]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:o},r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const o={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.addresses&&o.addresses.length===n.limits.addresses)throw new Er('Decode error - map field "addresses" had too many elements');o.addresses.push(vm.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&o.protocols.length===n.limits.protocols)throw new Er('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break;case 4:o.publicKey=t.bytes();break;case 5:o.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&o.metadata.size===n.limits.metadata)throw new Sr('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());o.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&o.tags.size===n.limits.tags)throw new Sr('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});o.tags.set(r.key,r.value);break}default:t.skipType(7&r)}}return o}))),n),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(wm||(wm={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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,r={})=>{const n={multiaddr:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.multiaddr=e.bytes();break;case 2:n.isCertified=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(vm||(vm={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((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,r={})=>{const n={value:0},o=null==t?e.len:e.pos+t;for(;e.pos<o;){const t=e.uint32();switch(t>>>3){case 1:n.value=e.uint32();break;case 2:n.expiry=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Em||(Em={}));const Am="/",km=(new TextEncoder).encode(Am),Cm=km[0];class Im{_buf;constructor(e,t){if("string"==typeof e)this._buf=xt(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Cm)throw new Error("Invalid key")}toString(e="utf8"){return Zr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Im(e.join(Am))}static random(){return new Im(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Im(e):"function"==typeof e.uint8Array?new Im(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=km),this._buf[0]!==Cm){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Cm,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Cm;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],o=r[e];if(n<o)return!0;if(n>o)return!1}return t.length<r.length}reverse(){return Im.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Am).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Im(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Am)||(e+=Am),e+=this.type(),new Im(e)}parent(){const e=this.list();return 1===e.length?new Im(Am):new Im(e.slice(0,-1).join(Am))}child(e){return this.toString()===Am?e:e.toString()===Am?this:new Im(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){return Im.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))]);var t}}const xm="/peers/";function Tm(e){if(!$o(e)||null==e.type)throw new Ws("Invalid PeerId");const t=e.toCID().toString();return new Im(`${xm}${t}`)}async function _m(e,t,r){const n=new Map;for(const o of r){if(null==o)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Is(o.multiaddr)),!Cs(o.multiaddr))throw new Ws("Multiaddr was invalid");if(!await t(e,o.multiaddr))continue;const r=o.isCertified??!1,s=o.multiaddr.toString(),i=n.get(s);null!=i?o.isCertified=i.isCertified||r:n.set(s,{multiaddr:o.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 Nm(e,t,r,n){if(null==t)throw new Ws("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Ws("publicKey bytes do not match peer id publicKey bytes");const o=n.existingPeer;if(null!=o&&!e.equals(o.id))throw new Ws("peer id did not match existing peer id");let s,i=o?.addresses??[],a=new Set(o?.protocols??[]),c=o?.metadata??new Map,l=o?.tags??new Map,u=o?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(i=[],null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Pm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Lm})),null!=t.tags&&(l=Pm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Bm,map:Om})),null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Pm([...c.entries()],{validate:Lm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Pm([...r.entries()],{validate:Bm,map:Om})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=o?.id.publicKey?s=Wu(o.id.publicKey):null!=t.publicKey?s=Wu(t.publicKey):null!=e.publicKey&&(s=Wu(e.publicKey));const h={addresses:await _m(e,n.addressFilter??(async()=>!0),i),protocols:[...a.values()].sort(((e,t)=>e.localeCompare(t))),metadata:c,tags:l,publicKey:s,peerRecordEnvelope:u};return"RSA"!==e.type&&delete h.publicKey,h}function Pm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,o]of e.sort((([e],[t])=>e.localeCompare(t))))null!=o&&r.set(n,t.map?.(n,o)??o);return r}function Lm(e,t){if("string"!=typeof e)throw new Ws("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Ws("Metadata value must be a Uint8Array")}function Bm(e,t){if("string"!=typeof e)throw new Ws("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Ws("Tag value must be an integer");if(t.value<0||t.value>100)throw new Ws("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Ws("Tag ttl must be an integer");if(t.ttl<0)throw new Ws("Tag ttl must be between greater than 0")}}function Om(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 Rm(e,t){const r=e.toString().split("/")[2];return Sm(ih(yt.parse(r,he)),t)}class Dm{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){const t=Object.assign({},bm,e);return null==mm&&(mm=(e=>{if(e=Object.assign({},fm,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return sm.addEventListener("message",dm(e,"requestReadLock",im,am,cm)),sm.addEventListener("message",dm(e,"requestWriteLock",lm,um,hm)),e}return{isWorker:!0,readLock:e=>pm(e,im,cm,am),writeLock:e=>pm(e,lm,hm,um)}})(t),!0!==mm.isWorker&&(mm.addEventListener("requestReadLock",(e=>{null!=gm[e.data.name]&&gm[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),mm.addEventListener("requestWriteLock",(async e=>{null!=gm[e.data.name]&&gm[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==gm[t.name]&&(gm[t.name]=((e,t)=>{if(!0===mm.isWorker)return{readLock:mm.readLock(e,t),writeLock:mm.writeLock(e,t)};const r=new Cg({concurrency:1});let n;return{async readLock(){if(null!=n)return ym(n,t);n=new Cg({concurrency:t.concurrency,autoStart:!1});const e=n,o=ym(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),o},writeLock:async()=>(n=null,ym(r,t))}})(t.name,t)),gm[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Tm(e))}async delete(e){if(this.peerId.equals(e))throw new Ws("Cannot delete self peer");await this.datastore.delete(Tm(e))}async load(e){return Sm(e,await this.datastore.get(Tm(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#P(e),o=await Nm(e,t,"patch",{addressFilter:this.addressFilter});return this.#L(e,o,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#P(e),o=await Nm(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,o,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#P(e),o=await Nm(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,o,r,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e){return null==e?{}:{prefix:xm,filters:(e.filters??[]).map((e=>({key:t,value:r})=>e(Rm(t,r)))),orders:(e.orders??[]).map((e=>(t,r)=>e(Rm(t.key,t.value),Rm(r.key,r.value))))}}(e??{}))){const e=Rm(t,r);e.id.equals(this.peerId)||(yield e)}}async#P(e){try{const t=await this.datastore.get(Tm(e));return{existingBuf:t,existingPeer:Sm(e,t)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}return{}}async#L(e,t,r,n){const o=wm.encode(t);return null!=r&&Cn(o,r)?{peer:Sm(e,o),previous:n,updated:!1}:(await this.datastore.put(Tm(e),o),{peer:Sm(e,o),previous:n,updated:!0})}}class Um{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 Dm(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");const r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const 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");const t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await An(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");const 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");const 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");const 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");const r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{const r=await this.store.save(e,t);return this.#B(e,r),r.peer}finally{this.log.trace("save release write lock"),r()}}async patch(e,t){this.log.trace("patch await write lock");const r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{const r=await this.store.patch(e,t);return this.#B(e,r),r.peer}finally{this.log.trace("patch release write lock"),r()}}async merge(e,t){this.log.trace("merge await write lock");const r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{const r=await this.store.merge(e,t);return this.#B(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){const r=await cp.openAndCertify(e,ip.DOMAIN),n=ih(r.publicKey.toCID());if(!1===t?.equals(n))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n),!1;const o=ip.createFromProtobuf(r.payload);let s;try{s=await this.get(n)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=s?.peerRecordEnvelope){const e=await cp.createFromProtobuf(s.peerRecordEnvelope),t=ip.createFromProtobuf(e.payload);if(t.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}#B(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}Error,Error,Error,Error,Error,Error;class Mm extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=Mm.name;code=Mm.code;constructor(e="Not Found"){super(e)}}Error;const Fm=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},$m=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[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}}}(e),{value:o,done:s}=n.next();if(!0===s)return function*(){}();const i=t(o,r++);if("function"==typeof i.then)return async function*(){await i&&(yield o);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===i&&(yield o);for(const e of n)a(e,r++)&&(yield e)}()},qm=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await An(e);yield*r.sort(t)}():function*(){const r=An(e);yield*r.sort(t)}()},Hm=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()};class jm{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const 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 Fm(this.putMany(e,r)),e=[],await Fm(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=$m(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>$m(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>qm(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=$m(r,(()=>t++>=n))}return null!=e.limit&&(r=Hm(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=$m(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>$m(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>qm(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=$m(r,(()=>n++>=t))}return null!=e.limit&&(r=Hm(r,e.limit)),r}}class Vm extends jm{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new Mm;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new Im(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Im(e)}}const zm=e=>e;function Km(e,t){const r=e.getPeerId();return null!=r&&nh(r).equals(t)&&(e=e.decapsulate(Is(`/p2p/${t.toString()}`))),e}class Gm{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){const{listen:r=[],announce:n=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.observed=new Map,this.announceFilter=t.announceFilter??zm,this._updatePeerStoreAddresses=function(e){let t;return function(){clearTimeout(t),t=setTimeout((function(){t=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>Is(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=>Is(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>Is(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>Is(e)))}addObservedAddr(e){const t=(e=Km(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=Km(e,this.components.peerId)).toString(),r=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),r||this._updatePeerStoreAddresses()}removeObservedAddr(e){const t=(e=Km(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()))),e=e.concat(Array.from(this.observed).filter((([e,t])=>t.confident)).map((([e])=>e)));const t=new Set(e);return this.announceFilter(Array.from(t).map((e=>Is(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}function Wm(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}var Jm;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(Jm||(Jm={}));class Xm extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class Ym extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Zm extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class Qm extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class ey extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class ty extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class ry extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class ny extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class oy extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class sy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class iy extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class ay extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class cy extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class ly extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class uy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=Zg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>Wm(e))).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")}}const hy=["metrics","connectionProtector","dns"],dy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function py(e){return Array.isArray(e?.[Ju])?e[Ju]:[]}function fy(e){return Array.isArray(e?.[Xu])?e[Xu]:[]}function gy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function my(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(pp(`${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}}class yy{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return em(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach(((t,r)=>{e(t.value,t.key,this)}))}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return em(this.map.values(),(e=>e.key))}values(){return em(this.map.values(),(e=>e.value))}get size(){return this.map.size}}function by(e){if($o(e))return{peerId:e,multiaddrs:[]};let t;if(Array.isArray(e)||(e=[e]),e.length>0){const r=e[0].getPeerId();t=null==r?void 0:nh(r),e.forEach((e=>{if(!Cs(e))throw new si("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Ws("Multiaddrs must all have the same peer id or have no peer id")}else{const e=nh(r);if(!0!==t?.equals(e))throw new Ws("Multiaddrs must all have the same peer id or have no peer id")}}))}return{peerId:t,multiaddrs:e}}const wy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],vy={maxConnections:100,allow:[]};class Ey{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??vy.maxConnections,this.allow=t.allow??vy.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;const r=new yy;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const n=this.sortConnections(e,r),o=Math.max(t-this.maxConnections,0),s=[];for(const 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===o)break;await Promise.all(s.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??wy;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-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<t.streams.length?-1:0)).sort(((e,r)=>{const n=t.get(e.remotePeer)??0,o=t.get(r.remotePeer)??0;return n>o?1:n<o?-1:0}))}}const Sy="last-dial-failure",Ay="last-dial-success";class ky 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 Cy(e,t,r,n){const o=new ky(n?.errorMessage,n?.errorCode);return!0===r?.aborted?Promise.reject(o):new Promise(((s,i)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,c),null!=n?.errorEvent&&e.removeEventListener(n.errorEvent,l)}const c=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return a(),void i(e)}a(),s(e)},l=e=>{a(),i(e.detail)},u=()=>{a(),i(o)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Iy{deferred;signal;constructor(e){this.signal=e,this.deferred=$n(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ks)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class xy{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,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Ks),this.cleanup())}async join(e={}){const t=new Iy(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();const e=await ch(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 Ty extends xo{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??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<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new If;const r=new xy(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then((e=>(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<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("error",{detail:e}),this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Ks)})),this.clear()}async onEmpty(e){0!==this.size&&await Cy(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Cy(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Cy(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Vn({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},o=e=>{r(e.detail)},s=()=>{r()},i=()=>{r(new Ks("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("error",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",i);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",i),r()}}}class _y extends Ty{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function Ny(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}function Py(e,t){const r=Dp.exactMatch(e.multiaddr),n=Dp.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const o=Vp.exactMatch(e.multiaddr),s=Vp.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;const i=Hp.exactMatch(e.multiaddr),a=Hp.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;const c=Yp.exactMatch(e.multiaddr),l=Yp.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=Kp.exactMatch(e.multiaddr),h=Kp.exactMatch(t.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=Wp.exactMatch(e.multiaddr),p=Wp.exactMatch(t.multiaddr);return d&&!p?-1:!d&&p?1:0}function Ly(e,t){const r=fp(e.multiaddr),n=fp(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function By(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Oy(e,t){const r=Xp.exactMatch(e.multiaddr),n=Xp.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class Ry{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??25,this.maxDialQueueLength=t.maxDialQueueLength??500,this.dialTimeout=t.dialTimeout??5e3,this.connections=t.connections??new yy,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))ks.set(e,r);this.queue=new _y({concurrency:t.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{e.detail.name!==Ks.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=by(e),o=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if("open"===o?.status)return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new pg("dial-queue:already-connected")),o;const s=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=s){this.log("joining existing dial target for %p",r);for(const e of n)s.options.multiaddrs.add(e.toString());return t.onProgress?.(new pg("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new pi("Dial queue is full");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new pg("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e?.onProgress?.(new pg("dial-queue:start-dial"));const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),e?.onProgress?.(new pg("dial-queue:calculated-addresses",n)),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let o=0;const s=[];for(const i of n){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,r),new pi("Peer had more than maxPeerAddrsToDial");o++;try{const n=await this.components.transportManager.dial(i.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",i.multiaddr);try{await this.components.peerStore.merge(n.remotePeer,{multiaddrs:[n.remoteAddr],metadata:{[Ay]:xt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return n}catch(e){if(this.log.error("dial failed to %a",i.multiaddr,e),null!=r)try{await this.components.peerStore.merge(r,{metadata:{[Sy]:xt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new hi(e.message);s.push(e)}}if(1===s.length)throw s[0];throw new AggregateError(s,"All multiaddr dials failed")}finally{t.clear()}}),{peerId:r,priority:t.priority??zy,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){return Ny([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:Is(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new pi("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new ny("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const 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("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const 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){"NoPeerRoutersError"!==t.name&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let o=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of ks.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(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){const t=`/p2p/${e.toString()}`;o=o.map((e=>{const r=e.multiaddr.protos().pop();return!0===r?.path?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const s=o.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),i=new Map;for(const e of s){const t=e.multiaddr.toString(),r=i.get(t);null==r?i.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...i.values()];if(0===a.length)throw new oy("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(Py).sort(By).sort(Oy).sort(Ly):c.sort(this.addressSorter);if(0===l.length)throw new ny("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!Xp.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const Dy="keep-alive";class Uy extends Ty{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var My=__webpack_require__(5617);const Fy=Object.prototype.toString,$y=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class qy extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Hy=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class jy{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Uy({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);Vy(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const o=My.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});const i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt((async s=>{try{const t=await e(s);i(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof qy)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Fy.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:$y.has(e.message))}(e))throw e;if(Hy(e,s,t),await t.shouldRetry(e)||(o.stop(),n(e)),await t.onFailedAttempt(e),!o.retry(e))throw o.mainError()}catch(e){Hy(e,s,t),i(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(Dy)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>Vy(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}}function Vy(e){for(const t of e.tags.keys())if(t.startsWith(Dy))return!0;return!1}const zy=50;class Ky{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Ws("Connection Manager maxConnections must be greater than 0");this.connections=new yy,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map((e=>Is(e))),this.deny=(t.deny??[]).map((e=>Is(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new xf({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Ey({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ry(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Rg},connections:this.connections}),this.reconnectQueue=new jy({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const 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:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)Wm(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)Wm(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const 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){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),o=this.connections.get(r)??[];o.push(t),this.connections.set(r,o),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter((e=>e.id!==t.id));this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),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(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new di("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=by(e);if(this.peerId.equals(r))throw new oi("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new pg("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??zy});if("open"!==n.status)throw new Zs("Remote closed connection during opening");let o=this.connections.get(n.remotePeer);null==o&&(o=[],this.connections.set(n.remotePeer,o));let s=!1;for(const e of o)if(e.id===n.id&&(s=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new si("Duplicate multiaddr connection")),e;return s||o.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const 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()){const 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<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>Is(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Gy{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,o=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class Wy{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Gy(e.interval??5e3),this.failure=new Gy(e.interval??5e3),this.next=new Gy(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??2e3,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){const t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),r=AbortSignal.timeout(t),n=Ny([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class Jy{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new Wy({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ju]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=ph(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(Wf(32),{signal:r}),n.read(32,{signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Xy{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";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 Zm("No content routers available");const r=this,n=new rm;for await(const o of zn(...r.routers.map((r=>r.findProviders(e,t)))))null!=o&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),n.has(o.id)||(n.add(o.id),yield o))}async provide(e,t={}){if(0===this.routers.length)throw new Zm("No content 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 di;await Promise.all(this.routers.map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new di;return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class Yy{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const o=t.hashV(e,r),s=g(n);for(let e=0;e<s.length;e++)s[e]=o[e];0===s.length&&(s[0]=7),this.fp=s,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Cn(this.fp,e.fp)}}function Zy(e,t){return Math.floor(Math.random()*(t-e))+e}class Qy{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Yy))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Yy))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Yy))throw new TypeError("Invalid Fingerprint");const t=Zy(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Yy))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const eb={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},tb={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},rb=new globalThis.TextEncoder;__webpack_require__(8437);const nb={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!eb[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const n=eb[t];let o=tb[t],s=e;for(;s.length>0;){const e=rb.encodeInto(s,r);s=s.slice(e.read);for(let s=0;s<e.written;s++)o^=BigInt(r[s]),o=BigInt.asUintN(t,o*n)}return o}(e,t,r);e=rb.encode(e)}return function(e,t){const r=eb[t];let n=tb[t];for(let o=0;o<e.length;o++)n^=BigInt(e[o]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),xt(t,"base16")}(nb.hash(e,t))};class ob{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??nb,this.seed=e.seed??Zy(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=xt(e));const t=new Yy(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Qy(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Qy(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const o=[r,n];let s=o[Zy(0,o.length-1)];null==this.buckets[s]&&(this.buckets[s]=new Qy(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[s].swap(t);if(null!=e&&(s=(s^e.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new Qy(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=xt(e));const t=new Yy(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const o=(r^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){"string"==typeof e&&(e=xt(e));const t=new Yy(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const o=(r^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const sb={1:.5,2:.84,4:.95,8:.98};function ib(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=sb[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class ab{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??nb,this.seed=e.seed??Zy(0,Math.pow(2,10)),this.filterSeries=[new ob({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=xt(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ob({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=xt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=xt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce(((e,t)=>e+t.count),0)}}const cb=globalThis.CustomEvent??Event;class lb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Qm("No peer routers available");if(e.toString()===this.peerId.toString())throw new ey("Should not try to find self");const r=this,n=zn(...this.routers.map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}),e;throw new ni}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Qm("No peer routers available");const r=this,n=function(e,t=.001,r){return new ab({...ib(1024,t),...r??{}})}();for await(const o of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=null!=t.ordered&&t.ordered,o=new EventTarget,s=[];let i,a=$n(),c=$n(),l=!1,u=!1;function h(){return n?s[0]?.done:Boolean(s.find((e=>e.done)))}function*d(){for(;s.length>0&&s[0].done;){const e=s[0];if(s.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<s.length;e++)if(s[e].done){const t=s[e];if(s.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(o.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(s.length===r&&(a=$n(),await a.promise),u)break;const e={done:!1};s.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,o.dispatchEvent(new cb("task-complete"))}),(t=>{e.done=!0,e.err=t,o.dispatchEvent(new cb("task-complete"))}))}l=!0,o.dispatchEvent(new cb("task-complete"))}catch(e){i=e,o.dispatchEvent(new cb("task-complete"))}}));;){if(h()||(c=$n(),await c.promise),null!=i)throw i;if(n?yield*d():yield*p(),l&&0===s.length)break}}(async function*(){const n=zn(...r.routers.map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=o&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),n.has(o.id.toMultihash().bytes)||(n.add(o.id.toMultihash().bytes),yield o))}}class ub extends xo{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=Ny([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=$n();const e=await Cy(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,this.walkController.signal;const e=Ny([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=Wf(32);let n=Date.now();for await(const o of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",o.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:o}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await ch(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).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 hb{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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new ty(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new ry(`Handler already registered for protocol ${e}`);const n=Dg.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 Ws("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;this.components.peerStore.get(t).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class db extends Map{metric;constructor(e){super();const{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){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class pb{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){const{name:t,metrics:r}=e;let n;return n=null!=r?new db({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Zf.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Ws("Transport must have a valid tag");if(this.transports.has(t))throw new Ws(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new ly(`No transport available for address ${String(e)}`);return t?.onProgress?.(new pg("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const 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(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new di("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t=[];for(const[r,n]of this.transports.entries()){const o=n.listenFilter(e),s=[];for(const e of o){this.log("creating listener for %s on %a",r,e);const t=n.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(r)??[];null==o&&(o=[],this.listeners.set(r,o)),o.push(t),t.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})})),t.addEventListener("close",(()=>{const e=o.findIndex((e=>e===t));o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})})),s.push(t.listen(e))}if(0!==s.length){if(null==(await Promise.allSettled(s)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==Zf.NO_FATAL)throw new oy(`Transport (${r}) could not listen on any available address`)}else t.push(r)}if(t.length===this.transports.size){const e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Zf.FATAL_ALL)throw new oy(e);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const fb="/multistream/1.0.0",gb=1024,mb=xt("\n");async function yb(e,t,r){await e.write(t,r)}async function bb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==mb[0])throw t.log.error("Invalid mss message - missing newline",r),new li("Missing newline");return r.sublist(0,-1)}(e,t);return Zr(r.subarray())}async function wb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=yh(e,{...r,maxDataLength:gb,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await bb(n,r);if(r.log.trace('handle: read "%s"',e),e!==fb){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await yb(n,xt(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await yb(n,xt("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const o=new _n(...t.map((e=>Ln.single(xt(`${e}\n`)))),xt("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await yb(n,o,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',fb,e),await yb(n,xt(`${fb}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',fb,e)}}async function vb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),o=e.source;let s=!1,i=!1;const a=$n();let c=!1,l=!1;const u=$n();let h=!1,d=!1;const p=$n(),f=yh({sink:n,source:o},{...r,maxDataLength:gb});async function g(){if(i)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;i=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',fb,t),await f.writeV([xt(`${fb}\n`),xt(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',fb,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await bb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===fb&&(e=await bb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new ci("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{i=!1,s=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const o of e){if(l&&await u.promise,c)yield o;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',fb,t,o.byteLength);const e=`${t}\n`;yield new _n(Uint8Array.from([19]),xt(`${fb}\n`),_(e.length),xt(e),o).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',fb,t,o.byteLength),c=!0,l=!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){const 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){const 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){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await ch(Promise.all(r),e?.signal):(s=!0,i=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=yh(e,{...r,maxDataLength:gb}),o=t.shift();if(null==o)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',fb,o);const s=xt(`${fb}\n`),i=xt(`${o}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[s,i],r),r.log.trace("select: reading multistream-select header");let a=await bb(n,r);if(r.log.trace('select: read "%s"',a),a===fb&&(r.log.trace("select: reading protocol response"),a=await bb(n,r),r.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(const e of t){r.log.trace('select: write "%s"',e),await yb(n,xt(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await bb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new ci("protocol selection failed")}const Eb=Symbol.for("@libp2p/connection");class Sb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:o,abort:s,getStreams:i}=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.limits=e.limits,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=o,this._abort=s,this._getStreams=i,this.tags=[]}[Symbol.toStringTag]="Connection";[Eb]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ys("the connection is being closed");if("closed"===this.status)throw new Zs("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new fi("Cannot open protocol stream on limited connection");const 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){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{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){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function Ab(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class kb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=new Map,t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new sy(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){try{if(this.metrics.dials?.increment({inbound:!0}),!await this.components.connectionManager.acceptIncomingConnection(e))throw new iy("connection denied");return await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(e){throw this.metrics.errors?.increment({inbound:!0}),e}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;return null!=r&&(n=nh(r),await this.shouldBlockConnection("denyOutboundConnection",n,e)),await this._performUpgrade(e,"outbound",t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),e}}async _performUpgrade(e,t,r){let n,o,s,i,a;const c=Ny([AbortSignal.timeout("inbound"===t?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),r.signal]);r.signal=c,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),l=await n.protect(e,r))}try{if(n=l,!0!==r?.skipEncryption){r?.onProgress?.(new pg(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:o,protocol:a}=await("inbound"===t?this._encryptInbound(l,{...r,signal:c}):this._encryptOutbound(l,{...r,signal:c})));const e={...l,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new si(`${t} connection that skipped encryption must have a peer id`);const n=nh(r);a="native",o=n}if(o.equals(this.components.peerId)){const t=new oi("Can not dial self");throw e.abort(t),t}if(s=n,null!=r?.muxerFactory)i=r.muxerFactory;else if(this.streamMuxers.size>0){r?.onProgress?.(new pg(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...l,...n},this.streamMuxers,r):this._multiplexOutbound({...l,...n},this.streamMuxers,r));i=e.muxerFactory,s=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}finally{c.clear()}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:s,muxerFactory:i,remotePeer:o,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:o,remotePeer:s,muxerFactory:i,limits:a}=e;let c,l,u;null!=i&&(c=i.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),r=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout),{stream:n,protocol:o}=await wb(e,t,{signal:r,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",o);const i=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(o,this.components.registrar);if(Ab(o,"inbound",u)===i){const t=new gi(`Too many inbound protocol streams for protocol "${o}" - limit ${i}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=o,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(s,{protocols:[o]}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:o})})).catch((async t=>{u.log.error("error handling incoming stream id %s - %e",e.id,t),null==e.timeline.close&&await e.close()}))}}),l=async(t,n={})=>{if(null==c)throw new ay("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const o=await c.newStream();u.log.trace("started new stream %s for protocols %s",o.id,t);try{if(null==n.signal){o.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}o.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await vb(o,t,{...n,log:o.log,yieldBytes:!0});o.log.trace("selected protocol %s",r);const i=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=Ab(r,"outbound",u);if(a>=i){const e=new mi(`Too many outbound protocol streams for protocol "${r}" - ${a}/${i}`);throw o.abort(e),e}return await this.components.peerStore.merge(s,{protocols:[r]}),o.source=e.source,o.sink=e.sink,o.protocol=r,null!=e.closeWrite&&(o.closeWrite=e.closeWrite),null!=e.closeRead&&(o.closeRead=e.closeRead),null!=e.close&&(o.close=e.close),this.components.metrics?.trackProtocolStream(o,u),o}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==o.timeline.close&&o.abort(n),n}},Promise.all([c.sink(o.source),o.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer - %e",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:s,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new ay("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],close:async e=>{await(c?.close(e)),await n.close(e)},abort:e=>{n.abort(e),c?.abort(e)}},u=new Sb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:o,options:s}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==s.runOnLimitedConnection)throw new fi("Cannot open protocol stream on limited connection");o({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:o}=await wb(e,r,{...t,log:e.log}),s=this.connectionEncrypters.get(o);if(null==s)throw new cy(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await s.secureInbound(n,t),protocol:o}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new cy(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:o}=await vb(e,r,{...t,log:e.log,yieldBytes:!0}),s=this.connectionEncrypters.get(o);if(null==s)throw new cy(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await s.secureOutbound(n,t),protocol:o}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new cy(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:o,protocol:s}=await vb(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",s),{stream:o,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new ay(String(t))}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:o,protocol:s}=await wb(e,n,{...r,log:e.log});return{stream:o,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new ay(String(t))}}}class Cb extends xo{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new xo,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??Zg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new uy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!dy.includes(r)){const e=t.components[r];if(null==e&&!hy.includes(r))throw new Xm(`${r} not set`);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:"2.1.8"},logger:this.logger,events:t,datastore:e.datastore??new Vm,connectionGater:my(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new Um(e,t)}(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){const 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 kb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map(((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components)))),streamMuxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new pb(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ky(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Jy(this.components,e.connectionMonitor)),this.configureComponent("registrar",new hb(this.components)),this.configureComponent("addressManager",new Gm(this.components,e.addresses));const o=(e.peerRouters??[]).map(((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new lb(this.components,{routers:o}));const s=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Xy(this.components,{routers:s})),this.configureComponent("randomWalk",new ub(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#O(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[Fg]&&(this.log("registering service %s for content routing",t),s.push(r[Fg])),null!=r[$g]&&(this.log("registering service %s for peer routing",t),o.push(r[$g])),null!=r[Ad]&&(this.log("registering service %s for peer discovery",t),r[Ad].addEventListener?.("peer",(e=>{this.#O(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of py(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of fy(r))if(!0!==t[e])throw new Ym(`Service "${gy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(n)}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(){const e=new rm;for(const 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)throw new Ws("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ws("no protocols were provided to open a 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={}){Cs(e)&&(e=nh(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{const t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=kn([xt("/pk/"),e.toMultihash().bytes]),n=Gu(await this.contentRouting.get(r,t));return 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)}#O(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}}const Ib="bootstrap",xb={store:1,filter:2,lightPush:2};var Tb=__webpack_require__(495),_b=__webpack_require__.t(Tb,2);const Nb=BigInt(0),Pb=BigInt(1),Lb=BigInt(2),Bb=BigInt(3),Ob=BigInt(8),Rb=Object.freeze({a:Nb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Pb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Db=(e,t)=>(e+t/Lb)/t,Ub={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=Rb,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Pb*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Db(s*e,t),c=Db(-n*e,t);let l=aw(e-a*r-c*o,t),u=aw(-a*n-c*s,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}};function Mb(e){const{a:t,b:r}=Rb,n=aw(e*e),o=aw(n*e);return aw(o+t*e+r)}const Fb=Rb.a===Nb;class $b extends Error{constructor(e){super(e)}}function qb(e){if(!(e instanceof Hb))throw new TypeError("JacobianPoint expected")}class Hb{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof zb))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(zb.ZERO)?Hb.ZERO:new Hb(e.x,e.y,Pb)}static toAffineBatch(e){const t=function(e,t=Rb.P){const r=new Array(e.length),n=lw(e.reduce(((e,n,o)=>n===Nb?e:(r[o]=e,aw(e*n,t))),Pb),t);return e.reduceRight(((e,n,o)=>n===Nb?e:(r[o]=aw(e*r[o],t),aw(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return Hb.toAffineBatch(e).map(Hb.fromAffine)}equals(e){qb(e);const{x:t,y:r,z:n}=this,{x:o,y:s,z:i}=e,a=aw(n*n),c=aw(i*i),l=aw(t*c),u=aw(o*a),h=aw(aw(r*i)*c),d=aw(aw(s*n)*a);return l===u&&h===d}negate(){return new Hb(this.x,aw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=aw(e*e),o=aw(t*t),s=aw(o*o),i=e+o,a=aw(Lb*(aw(i*i)-n-s)),c=aw(Bb*n),l=aw(c*c),u=aw(l-Lb*a),h=aw(c*(a-u)-Ob*s),d=aw(Lb*t*r);return new Hb(u,h,d)}add(e){qb(e);const{x:t,y:r,z:n}=this,{x:o,y:s,z:i}=e;if(o===Nb||s===Nb)return this;if(t===Nb||r===Nb)return e;const a=aw(n*n),c=aw(i*i),l=aw(t*c),u=aw(o*a),h=aw(aw(r*i)*c),d=aw(aw(s*n)*a),p=aw(u-l),f=aw(d-h);if(p===Nb)return f===Nb?this.double():Hb.ZERO;const g=aw(p*p),m=aw(p*g),y=aw(l*g),b=aw(f*f-m-Lb*y),w=aw(f*(y-b)-h*m),v=aw(n*i*p);return new Hb(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Hb.ZERO;if("bigint"==typeof e&&e===Nb)return t;let r=iw(e);if(r===Pb)return this;if(!Fb){let e=t,n=this;for(;r>Nb;)r&Pb&&(e=e.add(n)),n=n.double(),r>>=Pb;return e}let{k1neg:n,k1:o,k2neg:s,k2:i}=Ub.splitScalar(r),a=t,c=t,l=this;for(;o>Nb||i>Nb;)o&Pb&&(a=a.add(l)),i&Pb&&(c=c.add(l)),l=l.double(),o>>=Pb,i>>=Pb;return n&&(a=a.negate()),s&&(c=c.negate()),c=new Hb(aw(c.x*Ub.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=Fb?128/e+1:256/e+1,r=[];let n=this,o=n;for(let s=0;s<t;s++){o=n,r.push(o);for(let t=1;t<2**(e-1);t++)o=o.add(n),r.push(o);n=o.double()}return r}wNAF(e,t){!t&&this.equals(Hb.BASE)&&(t=zb.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&Vb.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=Hb.normalizeZ(n),Vb.set(t,n)));let o=Hb.ZERO,s=Hb.BASE;const i=1+(Fb?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<i;t++){const r=t*a;let i=Number(e&c);e>>=u,i>a&&(i-=l,e+=Pb);const h=r,d=r+Math.abs(i)-1,p=t%2!=0,f=i<0;0===i?s=s.add(jb(p,n[h])):o=o.add(jb(f,n[d]))}return{p:o,f:s}}multiply(e,t){let r,n,o=iw(e);if(Fb){const{k1neg:e,k1:s,k2neg:i,k2:a}=Ub.splitScalar(o);let{p:c,f:l}=this.wNAF(s,t),{p:u,f:h}=this.wNAF(a,t);c=jb(e,c),u=jb(i,u),u=new Hb(aw(u.x*Ub.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:s}=this.wNAF(o,t);r=e,n=s}return Hb.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,o=this.equals(Hb.ZERO);null==e&&(e=o?Ob:lw(n));const s=e,i=aw(s*s),a=aw(i*s),c=aw(t*i),l=aw(r*a),u=aw(n*s);if(o)return zb.ZERO;if(u!==Pb)throw new Error("invZ was invalid");return new zb(c,l)}}function jb(e,t){const r=t.negate();return e?r:t}Hb.BASE=new Hb(Rb.Gx,Rb.Gy,Pb),Hb.ZERO=new Hb(Nb,Pb,Nb);const Vb=new WeakMap;class zb{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,Vb.delete(this)}hasEvenY(){return this.y%Lb===Nb}static fromCompressedHex(e){const t=32===e.length,r=ow(t?e:e.subarray(1));if(!gw(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=Rb,r=BigInt(6),n=BigInt(11),o=BigInt(22),s=BigInt(23),i=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=cw(l,Bb)*l%t,h=cw(u,Bb)*l%t,d=cw(h,Lb)*c%t,p=cw(d,n)*d%t,f=cw(p,o)*p%t,g=cw(f,i)*f%t,m=cw(g,a)*g%t,y=cw(m,i)*f%t,b=cw(y,Bb)*l%t,w=cw(b,s)*p%t,v=cw(w,r)*c%t,E=cw(v,Lb);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(Mb(r));const o=(n&Pb)===Pb;t?o&&(n=aw(-n)):!(1&~e[0])!==o&&(n=aw(-n));const s=new zb(r,n);return s.assertValidity(),s}static fromUncompressedHex(e){const t=ow(e.subarray(1,33)),r=ow(e.subarray(33,65)),n=new zb(t,r);return n.assertValidity(),n}static fromHex(e){const t=sw(e),r=t.length,n=t[0];if(32===r)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return zb.BASE.multiply(yw(e))}static fromSignature(e,t,r){const{r:n,s:o}=bw(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const s=uw(sw(e)),{n:i}=Rb,a=2===r||3===r?n+i:n,c=lw(a,i),l=aw(-s*c,i),u=aw(o*c,i),h=1&r?"03":"02",d=zb.fromHex(h+Qb(a)),p=zb.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return nw(this.toHex(e))}toHex(e=!1){const t=Qb(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Qb(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!gw(t)||!gw(r))throw new Error(e);const n=aw(r*r);if(aw(n-Mb(t))!==Nb)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new zb(this.x,aw(-this.y))}double(){return Hb.fromAffine(this).double().toAffine()}add(e){return Hb.fromAffine(this).add(Hb.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Hb.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=Hb.fromAffine(this),o=t===Nb||t===Pb||this!==zb.BASE?n.multiplyUnsafe(t):n.multiply(t),s=Hb.fromAffine(e).multiplyUnsafe(r),i=o.add(s);return i.equals(Hb.ZERO)?void 0:i.toAffine()}}function Kb(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function Gb(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${Yb(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:ow(r),left:e.subarray(t+2)}}zb.BASE=new zb(Rb.Gx,Rb.Gy),zb.ZERO=new zb(Nb,Nb);class Wb{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?Yb(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new Wb(rw(n.slice(0,64)),rw(n.slice(64,128)))}static fromDER(e){const t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:n}=function(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${Yb(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=Gb(e.subarray(2)),{data:n,left:o}=Gb(r);if(o.length)throw new Error(`Invalid signature: left bytes after parsing: ${Yb(o)}`);return{r:t,s:n}}(t?e:nw(e));return new Wb(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!fw(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!fw(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=Rb.n>>Pb;return this.s>e}normalizeS(){return this.hasHighS()?new Wb(this.r,aw(-this.s,Rb.n)):this}toDERRawBytes(){return nw(this.toDERHex())}toDERHex(){const e=Kb(tw(this.s)),t=Kb(tw(this.r)),r=e.length/2,n=t.length/2,o=tw(r),s=tw(n);return`30${tw(n+r+4)}02${s}${t}02${o}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return nw(this.toCompactHex())}toCompactHex(){return Qb(this.r)+Qb(this.s)}}function Jb(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const o=e[t];r.set(o,n),n+=o.length}return r}const Xb=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Yb(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r<e.length;r++)t+=Xb[e[r]];return t}const Zb=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Qb(e){if("bigint"!=typeof e)throw new Error("Expected bigint");if(!(Nb<=e&&e<Zb))throw new Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function ew(e){const t=nw(Qb(e));if(32!==t.length)throw new Error("Error: expected 32 bytes");return t}function tw(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function rw(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt(`0x${e}`)}function nw(e){if("string"!=typeof e)throw new TypeError("hexToBytes: expected string, got "+typeof e);if(e.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+e.length);const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++){const n=2*r,o=e.slice(n,n+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");t[r]=s}return t}function ow(e){return rw(Yb(e))}function sw(e){return e instanceof Uint8Array?Uint8Array.from(e):nw(e)}function iw(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&fw(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function aw(e,t=Rb.P){const r=e%t;return r>=Nb?r:t+r}function cw(e,t){const{P:r}=Rb;let n=e;for(;t-- >Nb;)n*=n,n%=r;return n}function lw(e,t=Rb.P){if(e===Nb||t<=Nb)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=aw(e,t),n=t,o=Nb,s=Pb,i=Pb,a=Nb;for(;r!==Nb;){const e=n/r,t=n%r,c=o-i*e,l=s-a*e;n=r,r=t,o=i,s=a,i=c,a=l}if(n!==Pb)throw new Error("invert: does not exist");return aw(o,t)}function uw(e,t=!1){const r=function(e){const t=8*e.length-256,r=ow(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=Rb;return r>=n?r-n:r}let hw,dw;class pw{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new 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 Cw.hmacSha256(this.k,...e)}hmacSync(...e){return dw(this.k,...e)}checkSync(){if("function"!=typeof dw)throw new $b("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new 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;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return Jb(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return Jb(...t)}}function fw(e){return Nb<e&&e<Rb.n}function gw(e){return Nb<e&&e<Rb.P}function mw(e,t,r,n=!0){const{n:o}=Rb,s=uw(e,!0);if(!fw(s))return;const i=lw(s,o),a=zb.BASE.multiply(s),c=aw(a.x,o);if(c===Nb)return;const l=aw(i*aw(t+r*c,o),o);if(l===Nb)return;let u=new Wb(c,l),h=(a.x===u.r?0:2)|Number(a.y&Pb);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function yw(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw new Error("Expected 32 bytes of private key");t=rw(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(32!==e.length)throw new Error("Expected 32 bytes of private key");t=ow(e)}if(!fw(t))throw new Error("Expected private key: 0 < key < n");return t}function bw(e){if(e instanceof Wb)return e.assertValidity(),e;try{return Wb.fromDER(e)}catch(t){return Wb.fromCompact(e)}}function ww(e){return ow(e.length>32?e.slice(0,32):e)}function vw(e){const t=ww(e),r=aw(t,Rb.n);return Ew(r<Nb?t:r)}function Ew(e){return ew(e)}const Sw={strict:!0};zb.BASE._setWindowSize(8);const Aw={node:_b,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},kw={},Cw={bytesToHex:Yb,hexToBytes:nw,concatBytes:Jb,mod:aw,invert:lw,isValidPrivateKey(e){try{return yw(e),!0}catch(e){return!1}},_bigintTo32Bytes:ew,_normalizePrivateKey:yw,hashToPrivateKey:e=>{if((e=sw(e)).length<40||e.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return ew(aw(ow(e),Rb.n-Pb)+Pb)},randomBytes:(e=32)=>{if(Aw.web)return Aw.web.getRandomValues(new Uint8Array(e));if(Aw.node){const{randomBytes:t}=Aw.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Cw.hashToPrivateKey(Cw.randomBytes(40)),precompute(e=8,t=zb.BASE){const r=t===zb.BASE?t:new zb(t.x,t.y);return r._setWindowSize(e),r.multiply(Bb),r},sha256:async(...e)=>{if(Aw.web){const t=await Aw.web.subtle.digest("SHA-256",Jb(...e));return new Uint8Array(t)}if(Aw.node){const{createHash:t}=Aw.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(Aw.web){const r=await Aw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Jb(...t),o=await Aw.web.subtle.sign("HMAC",r,n);return new Uint8Array(o)}if(Aw.node){const{createHmac:r}=Aw.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=kw[e];if(void 0===r){const t=await Cw.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Jb(t,t),kw[e]=r}return Cw.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof hw)throw new $b("sha256Sync is undefined, you need to set it");let r=kw[e];if(void 0===r){const t=hw(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Jb(t,t),kw[e]=r}return hw(r,...t)},_JacobianPoint:Hb};Object.defineProperties(Cw,{sha256Sync:{configurable:!1,get:()=>hw,set(e){hw||(hw=e)}},hmacSha256Sync:{configurable:!1,get:()=>dw,set(e){dw||(dw=e)}}});var Iw=__webpack_require__(1176);function xw(e){return new Uint8Array(Iw.keccak256.arrayBuffer(e))}function Tw(e,t,r){try{return function(e,t,r,n=Sw){let o;try{o=bw(e),t=sw(t)}catch(e){return!1}const{r:s,s:i}=o;if(n.strict&&o.hasHighS())return!1;const a=uw(t);let c;try{c=function(e){return e instanceof zb?(e.assertValidity(),e):zb.fromHex(e)}(r)}catch(e){return!1}const{n:l}=Rb,u=lw(i,l),h=aw(a*u,l),d=aw(s*u,l),p=zb.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&aw(p.x,l)===s}(Wb.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const _w="Invalid record id";function Nw(e,t){switch(t){case"udp":return Nw(e,"udp4")||Nw(e,"udp6");case"tcp":return Nw(e,"tcp4")||Nw(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const o=t.slice(0,3);let s;switch(o){case"udp":s=r?e.get("udp6"):e.get("udp");break;case"tcp":s=r?e.get("tcp6"):e.get("tcp");break;default:return}return s?function(e,t,r,n){let o=Is("/"+e+"/"+ss(e,r));return o=o.encapsulate(Is("/"+t+"/"+ss(t,n))),o}(r?"ip6":"ip4",o,n,s):void 0}function Pw(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let o=0;return e.forEach((e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(o,e.bytes.length),o+=2,r.set(e.bytes,o),o+=e.bytes.length})),r}function Lw(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class Bw 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(){const e=this.get("id");if(!e)throw new Error("id not found.");return tn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(_w)}get rs(){const e=this.get("rs");if(e)return hn(e)}get rsv(){const e=this.get("rsv");if(e)return hn(e)}get ip(){return Ow(this,"ip","ip4")}set ip(e){Dw(this,"ip","ip4",e)}get tcp(){return Rw(this,"tcp","tcp")}set tcp(e){Uw(this,"tcp","tcp",e)}get udp(){return Rw(this,"udp","udp")}set udp(e){Uw(this,"udp","udp",e)}get ip6(){return Ow(this,"ip6","ip6")}set ip6(e){Dw(this,"ip6","ip6",e)}get tcp6(){return Rw(this,"tcp6","tcp")}set tcp6(e){Uw(this,"tcp6","tcp",e)}get udp6(){return Rw(this,"udp6","udp")}set udp6(e){Uw(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const o=e.slice(r,r+n);r+=n,t.push(Is(o))}return t}(e)}set multiaddrs(e){Mw(this,"multiaddrs",e,Pw)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Mw(this,"waku2",e,(e=>new Uint8Array([Lw(e)])))}}function Ow(e,t,r){const n=e.get(t);if(n)return ss(r,n)}function Rw(e,t,r){const n=e.get(t);if(n)return Number(ss(r,n))}function Dw(e,t,r,n){Mw(e,t,n,is.bind({},r))}function Uw(e,t,r,n){Dw(e,t,r,n?.toString(10))}function Mw(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function Fw(e,t){return async function(e,t,r={}){const{seed:n,m:o,d:s}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=sw(e),o=yw(t),s=[Ew(o),vw(n)];if(null!=r){!0===r&&(r=Cw.randomBytes(32));const e=sw(r);if(32!==e.length)throw new Error("sign: Expected 32 bytes of extra data");s.push(e)}return{seed:Jb(...s),m:ww(n),d:o}}(e,t,r.extraEntropy),i=new pw(32,32);let a;for(await i.reseed(n);!(a=mw(await i.generate(),o,s,r.canonical));)await i.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:o,recovered:s}=Object.assign({canonical:!0,der:!0},t),i=o?r.toDERRawBytes():r.toCompactRawBytes();return s?[i,n]:i}(a,r)}(xw(t),e,{der:!1})}const $w=new gn("enr");var qw,Hw;!function(e){e.TCP="tcp",e.UDP="udp"}(qw||(qw={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(Hw||(Hw={}));class jw extends Bw{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new jw(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=32===(r=e).byteLength?rc(r):33===r.byteLength?Vu(r):Eu(r);var r;if("secp256k1"!==t.type)throw new Error("Keypair type not implemented");return oh(t)}(e))}catch(e){$w.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=zb.fromHex(e).toRawBytes(!1);return en(xw(t.slice(1)))}(this.publicKey):void 0;throw new Error(_w)}getLocationMultiaddr=Nw.bind({},this);get shardInfo(){return this.rs&&this.rsv&&$w.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new 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(){const e=[];for(const t of Object.values(Hw)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const 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 new Error(_w);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return Tw(t,xw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(_w);return this.signature=await Fw(t,e),this.signature}}let Vw=!1,zw=!1;const Kw={debug:1,default:2,info:2,warning:3,error:4,off:5};let Gw=Kw.default,Ww=null;const Jw=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var Xw,Yw;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(Xw||(Xw={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(Yw||(Yw={}));const Zw="0123456789abcdef";class Qw{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==Kw[r]&&this.throwArgumentError("invalid log level name","logLevel",e),Gw>Kw[r]||console.log.apply(console,t)}debug(...e){this._log(Qw.levels.DEBUG,e)}info(...e){this._log(Qw.levels.INFO,e)}warn(...e){this._log(Qw.levels.WARNING,e)}makeError(e,t,r){if(zw)return this.makeError("censored error",t,{});t||(t=Qw.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=Zw[t[e]>>4],r+=Zw[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}`);const o=e;let s="";switch(t){case Yw.NUMERIC_FAULT:{s="NUMERIC_FAULT";const 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 Yw.CALL_EXCEPTION:case Yw.INSUFFICIENT_FUNDS:case Yw.MISSING_NEW:case Yw.NONCE_EXPIRED:case Yw.REPLACEMENT_UNDERPRICED:case Yw.TRANSACTION_REPLACED:case Yw.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const i=new Error(e);return i.reason=o,i.code=t,Object.keys(r).forEach((function(e){i[e]=r[e]})),i}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Qw.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"),Jw&&this.throwError("platform missing String.prototype.normalize",Qw.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Jw})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Qw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Qw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,Qw.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,Qw.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Qw.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",Qw.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Qw.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Ww||(Ww=new Qw("logger/5.7.0")),Ww}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Qw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),Vw){if(!e)return;this.globalLogger().throwError("error censorship permanent",Qw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}zw=!!e,Vw=!!t}static setLogLevel(e){const t=Kw[e.toLowerCase()];null!=t?Gw=t:Qw.globalLogger().warn("invalid log level - "+e)}static from(e){return new Qw(e)}}Qw.errors=Yw,Qw.levels=Xw;const ev=new Qw("bytes/5.7.0");function tv(e){return!!e.toHexString}function rv(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return rv(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function nv(e){return"number"==typeof e&&e==e&&e%1==0}function ov(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!nv(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!nv(r)||r<0||r>=256)return!1}return!0}function sv(e,t){if(t||(t={}),"number"==typeof e){ev.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),rv(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),tv(e)&&(e=e.toHexString()),iv(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":ev.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return rv(new Uint8Array(n))}return ov(e)?rv(new Uint8Array(e)):ev.throwArgumentError("invalid arrayify value","value",e)}function iv(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/)||t&&e.length!==2+2*t)}const av="0123456789abcdef";function cv(e,t){if(t||(t={}),"number"==typeof e){ev.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=av[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),tv(e))return e.toHexString();if(iv(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":ev.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(ov(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=av[(240&n)>>4]+av[15&n]}return t}return ev.throwArgumentError("invalid hexlify value","value",e)}const lv=new Qw("rlp/5.7.0");function uv(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function hv(e,t,r){let n=0;for(let o=0;o<r;o++)n=256*n+e[t+o];return n}function dv(e){if(Array.isArray(e)){let t=[];if(e.forEach((function(e){t=t.concat(dv(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=uv(t.length);return r.unshift(247+r.length),r.concat(t)}var t;iv(t=e)&&!(t.length%2)||ov(t)||lv.throwArgumentError("RLP object must be BytesLike","object",e);const r=Array.prototype.slice.call(sv(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=uv(r.length);return n.unshift(183+n.length),n.concat(r)}function pv(e,t,r,n){const o=[];for(;r<t+1+n;){const s=fv(e,r);o.push(s.result),(r+=s.consumed)>t+1+n&&lv.throwError("child data too short",Qw.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:o}}function fv(e,t){if(0===e.length&&lv.throwError("data too short",Qw.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&lv.throwError("data short segment too short",Qw.errors.BUFFER_OVERRUN,{});const n=hv(e,t+1,r);return t+1+r+n>e.length&&lv.throwError("data long segment too short",Qw.errors.BUFFER_OVERRUN,{}),pv(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&lv.throwError("data array too short",Qw.errors.BUFFER_OVERRUN,{}),pv(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&lv.throwError("data array too short",Qw.errors.BUFFER_OVERRUN,{});const n=hv(e,t+1,r);return t+1+r+n>e.length&&lv.throwError("data array too short",Qw.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:cv(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&lv.throwError("data too short",Qw.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:cv(e.slice(t+1,t+1+r))}}return{consumed:1,result:cv(e[t])}}const gv=new gn("enr:decoder");class mv{static fromString(e){if(!e.startsWith(jw.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${jw.RECORD_PREFIX}'`);return mv.fromRLP(xt(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=sv(e),r=fv(t,0);return r.consumed!==t.length&&lv.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(Qr);return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw new Error("Decoded ENR must be an array");if(e.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),o={};for(let e=0;e<n.length;e+=2)try{o[tn(n[e])]=n[e+1]}catch(t){gv.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const s=function(e){return e.length?BigInt("0x"+en(e)):BigInt(0)}(r),i=jw.create(o,s,t);return function(e,t,r,n){const o=Qr(cv(dv([e,...t])));if(!r.verify(o,n))throw new Error("Unable to verify ENR signature")}(r,n,i,t),i}(t)}}const yv=/^(\d{1,3}\.){3,3}\d{1,3}$/,bv=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,wv={name:"v4",size:4,isFormat:e=>yv.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let o=0;for(let s=0;s<n;){const n=e.charCodeAt(s++);46===n?(t[r++]=o,o=0):o=10*o+(n-48)}return t[r]=o,t},decode:(e,t)=>(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},vv={name:"v6",size:16,isFormat:e=>e.length>0&&bv.test(e),encode(e,t,r){let n=16+(r=~~r),o=-1,s=0,i=0,a=!0,c=!1;t=t||new Uint8Array(r+16);for(let l=0;l<e.length;l++){let u=e.charCodeAt(l);58===u?(a?-1!==o?(r<n&&(t[r]=0),r<n-1&&(t[r+1]=0),r+=2):r<n&&(o=r):(!0===c?(r<n&&(t[r]=i),r++):(r<n&&(t[r]=s>>8),r<n-1&&(t[r+1]=255&s),r+=2),s=0,i=0),a=!0,c=!1):46===u?(r<n&&(t[r]=i),r++,i=0,s=0,a=!1,c=!0):(a=!1,u>=97?u-=87:u>=65?u-=55:(u-=48,i=10*i+u),s=(s<<4)+u)}if(!1===a)!0===c?(r<n&&(t[r]=i),r++):(r<n&&(t[r]=s>>8),r<n-1&&(t[r+1]=255&s),r+=2);else if(0===o)r<n&&(t[r]=0),r<n-1&&(t[r+1]=0),r+=2;else if(-1!==o){r+=2;for(let e=Math.min(r-1,n-1);e>=o+2;e--)t[e]=t[e-2];t[o]=0,t[o+1]=0,o=r}if(o!==r&&-1!==o)for(r>n-2&&(r=n-2);n>o;)t[--n]=r<n&&r>o?t[--r]:0;else for(;r<n;)t[r++]=0;return t},decode(e,t){t=~~t;let r="";for(let n=0;n<16;n+=2)0!==n&&(r+=":"),r+=(e[t+n]<<8|e[t+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function Ev(e){if(wv.isFormat(e))return wv.size;if(vv.isFormat(e))return vv.size;throw Error(`Invalid ip address: ${e}`)}function Sv(e){switch(e){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+e}function Av(e){switch(e.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":case"*":return 255}return e.toUpperCase().startsWith("UNKNOWN_")?parseInt(e.slice(8)):0}function kv(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}function Cv(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}function Iv(e){switch(e){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+e}function xv(e){switch(e.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function Tv(e){if("number"==typeof e)return e;if(!e)return-1;switch(e.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}const t=e.match(/_(\d+)$/);return t?parseInt(t[1],10):-1}const _v=55296,Nv=56320;function Pv(e){let t=0;const r=e.length;for(let n=0;n<r;n+=1){const o=e.charCodeAt(n);if(o<=127)t+=1;else if(o<=2047)t+=2;else if((63488&o)!==_v)t+=3;else{const s=n+1;s===r||o>=Nv||(64512&e.charCodeAt(s))!==Nv?t+=3:(n=s,t+=4)}}return t}function Lv(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(Pv(e)+r));let o=r;for(let r=0;r<n;r+=1){let s=e.charCodeAt(r);if(s<=127)t[o++]=s;else if(s<=2047)t[o++]=192|(1984&s)>>6,t[o++]=128|63&s;else if((63488&s)!==_v)t[o++]=224|(61440&s)>>12,t[o++]=128|(4032&s)>>6,t[o++]=128|63&s;else{const i=r+1;if(i===n||s>=Nv)t[o++]=239,t[o++]=191,t[o++]=189;else{const n=e.charCodeAt(i);(64512&n)!==Nv?(t[o++]=239,t[o++]=191,t[o++]=189):(r=i,s=65536|(1023&s)<<10|1023&n,t[o++]=240|(1835008&s)>>18,t[o++]=128|(258048&s)>>12,t[o++]=128|(4032&s)>>6,t[o++]=128|63&s)}}}return Lv.bytes=o-r,t}function Bv(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let o=t;o<r;){const t=e[o++];let r;if(t<=128)r=t;else if(t>191&&t<224)r=(31&t)<<6|63&e[o++];else if(t>239&&t<365){r=((7&t)<<18|(63&e[o++])<<12|(63&e[o++])<<6|63&e[o++])-65536;const s=_v|r>>10&1023;n+=String.fromCharCode(s),r=Nv|1023&r}else r=(15&t)<<12|(63&e[o++])<<6|63&e[o++];n+=String.fromCharCode(r)}return Bv.bytes=r-t,n}Lv.bytes=0,Bv.bytes=0;const Ov=e=>e instanceof Uint8Array;function Rv(e){return"string"==typeof e?Pv(e):e.byteLength}function Dv(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):Lv(e)}function Uv(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return Lv(t,e,r),Lv.bytes}const Mv=Math.pow(2,24),Fv=Math.pow(2,16),$v=Math.pow(2,8),qv=(e,t)=>e[t]*Mv+e[t+1]*Fv+e[t+2]*$v+e[t+3],Hv=(e,t)=>e[t]<<8|e[t+1],jv=(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),Vv=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function zv(e,t,r,n,o){return r<0&&(n-=r,r=0),n<0&&(n=0),o<0?new Uint8Array(0):r>=t.length||n>=o?0:function(e,t,r,n,o){o-n>t.length-r&&(o=n+t.length-r);let s=o-n;const i=e.length-n;return s>i&&(s=i),(0!==n||o<e.length)&&(e=new Uint8Array(e.buffer,e.byteOffset+n,s)),t.set(e,r),s}(e,t,r,n,o)}function Kv({bytes:e=0,encode:t,decode:r,encodingLength:n}){return t.bytes=e,r.bytes=e,{encode:t,decode:r,encodingLength:n||(()=>e)}}const Gv=Kv({encode(e,t,r){t||(t=new Uint8Array(Gv.encodingLength(e))),r||(r=0);const n=r,o=e.replace(/^\.|\.$/gm,"");if(o.length){const e=o.split(".");for(let n=0;n<e.length;n++){const o=Uv(t,e[n],r+1);t[r]=o,r+=o+1}}return t[r++]=0,Gv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=[];let n=t,o=0,s=0,i=!1;for(;;){if(t>=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(s+=i?0:1,0===a)break;if(192&a){if(192&~a)throw new Error("Cannot decode name (bad label)");{if(t+1>e.length)throw new Error("Cannot decode name (buffer overflow)");const r=Hv(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,s+=i?0:1,i=!0}}else{if(t+a>e.length)throw new Error("Cannot decode name (buffer overflow)");if(o+=a+1,o>254)throw new Error("Cannot decode name (name too long)");r.push(Bv(e,t,t+a)),t+=a,s+=i?0:a}}return Gv.decode.bytes=s,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:Rv(e.replace(/^\.|\.$/gm,""))+2}),Wv=Kv({encode(e,t,r){t||(t=new Uint8Array(Wv.encodingLength(e))),r||(r=0);const n=Uv(t,e,r+1);return t[r]=n,Wv.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=Bv(e,t+1,t+1+r);return Wv.decode.bytes=r+1,n},encodingLength:e=>Rv(e)+1}),Jv=Kv({bytes:12,encode(e,t,r){t||(t=new Uint8Array(Jv.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),o="response"===e.type?32768:0;return Vv(t,e.id||0,r),Vv(t,n|o,r+2),Vv(t,e.questions.length,r+4),Vv(t,e.answers.length,r+6),Vv(t,e.authorities.length,r+8),Vv(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw new Error("Header must be 12 bytes");const r=Hv(e,t+2);return{id:Hv(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:Cv(r>>11&15),flag_aa:1==(r>>10&1),flag_tc:1==(r>>9&1),flag_rd:1==(r>>8&1),flag_ra:1==(r>>7&1),flag_z:1==(r>>6&1),flag_ad:1==(r>>5&1),flag_cd:1==(r>>4&1),rcode:kv(15&r),questions:new Array(Hv(e,t+4)),answers:new Array(Hv(e,t+6)),authorities:new Array(Hv(e,t+8)),additionals:new Array(Hv(e,t+10))}},encodingLength:()=>12}),Xv=Kv({encode(e,t,r){t||(t=new Uint8Array(Xv.encodingLength(e))),r||(r=0);const n=e.length;return Vv(t,n,r),zv(e,t,r+2,0,n),Xv.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Hv(e,t),n=e.slice(t+2,t+2+r);return Xv.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),Yv=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(Yv.encodingLength(e))),r||(r=0),Gv.encode(e,t,r+2),Vv(t,Gv.encode.bytes,r),Yv.encode.bytes=Gv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=Hv(e,t),n=Gv.decode(e,t+2);return Yv.decode.bytes=r+2,n},encodingLength:e=>Gv.encodingLength(e)+2}),Zv=Kv({encode(e,t,r){t||(t=new Uint8Array(Zv.encodingLength(e))),r||(r=0);const n=r;return r+=2,Gv.encode(e.mname,t,r),r+=Gv.encode.bytes,Gv.encode(e.rname,t,r),r+=Gv.encode.bytes,jv(t,e.serial||0,r),r+=4,jv(t,e.refresh||0,r),r+=4,jv(t,e.retry||0,r),r+=4,jv(t,e.expire||0,r),r+=4,jv(t,e.minimum||0,r),Vv(t,(r+=4)-n-2,n),Zv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=Gv.decode(e,t),t+=Gv.decode.bytes,n.rname=Gv.decode(e,t),t+=Gv.decode.bytes,n.serial=qv(e,t),t+=4,n.refresh=qv(e,t),t+=4,n.retry=qv(e,t),t+=4,n.expire=qv(e,t),t+=4,n.minimum=qv(e,t),t+=4,Zv.decode.bytes=t-r,n},encodingLength:e=>22+Gv.encodingLength(e.mname)+Gv.encodingLength(e.rname)}),Qv=Kv({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t<e.length;t++)if("string"==typeof e[t]&&(e[t]=Dv(e[t])),!Ov(e[t]))throw new Error("Must be a Buffer");t||(t=new Uint8Array(Qv.encodingLength(e))),r||(r=0);const n=r;return r+=2,e.forEach((function(e){t[r++]=e.length,zv(e,t,r,0,e.length),r+=e.length})),Vv(t,r-n-2,n),Qv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t;let n=Hv(e,t);t+=2;const o=[];for(;n>0;){const r=e[t++];if(--n,n<r)throw new Error("Buffer overflow");o.push(e.slice(t,t+r)),t+=r,n-=r}return Qv.decode.bytes=t-r,o},encodingLength(e){Array.isArray(e)||(e=[e]);let t=2;return e.forEach((function(e){t+="string"==typeof e?Rv(e)+1:e.length+1})),t}}),eE=Kv({encode(e,t,r){t||(t=new Uint8Array(eE.encodingLength(e))),r||(r=0),"string"==typeof e&&(e=Dv(e)),e||(e=new Uint8Array(0));const n=r;r+=2;const o=e.length;return zv(e,t,r,0,o),Vv(t,(r+=o)-n-2,n),eE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n=Hv(e,t);t+=2;const o=e.slice(t,t+n);return t+=n,eE.decode.bytes=t-r,o},encodingLength:e=>e?(Ov(e)?e.length:Rv(e))+2:2}),tE=Kv({encode(e,t,r){t||(t=new Uint8Array(tE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Wv.encode(e.cpu,t,r),r+=Wv.encode.bytes,Wv.encode(e.os,t,r),r+=Wv.encode.bytes,Vv(t,r-n-2,n),tE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=Wv.decode(e,t),t+=Wv.decode.bytes,n.os=Wv.decode(e,t),t+=Wv.decode.bytes,tE.decode.bytes=t-r,n},encodingLength:e=>Wv.encodingLength(e.cpu)+Wv.encodingLength(e.os)+2}),rE=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(rE.encodingLength(e))),r||(r=0),Gv.encode(e,t,r+2),Vv(t,Gv.encode.bytes,r),rE.encode.bytes=Gv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=Gv.decode(e,t+2);return rE.decode.bytes=Gv.decode.bytes+2,r},encodingLength:e=>Gv.encodingLength(e)+2}),nE=Kv({encode(e,t,r){t||(t=new Uint8Array(nE.encodingLength(e))),r||(r=0),Vv(t,e.priority||0,r+2),Vv(t,e.weight||0,r+4),Vv(t,e.port||0,r+6),Gv.encode(e.target,t,r+8);const n=Gv.encode.bytes+6;return Vv(t,n,r),nE.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Hv(e,t),n={};return n.priority=Hv(e,t+2),n.weight=Hv(e,t+4),n.port=Hv(e,t+6),n.target=Gv.decode(e,t+8),nE.decode.bytes=r+2,n},encodingLength:e=>8+Gv.encodingLength(e.target)}),oE=Kv({encode(e,t,r){const n=oE.encodingLength(e);return t||(t=new Uint8Array(oE.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=oE.ISSUER_CRITICAL),Vv(t,n-2,r),t[r+=2]=e.flags||0,r+=1,Wv.encode(e.tag,t,r),r+=Wv.encode.bytes,Uv(t,e.value,r),r+=Rv(e.value),oE.encode.bytes=n,t},decode(e,t){t||(t=0);const r=Hv(e,t),n=t+=2,o={};return o.flags=e[t],t+=1,o.tag=Wv.decode(e,t),t+=Wv.decode.bytes,o.value=Bv(e,t,n+r),o.issuerCritical=!!(o.flags&oE.ISSUER_CRITICAL),oE.decode.bytes=r+2,o},encodingLength:e=>Wv.encodingLength(e.tag)+Wv.encodingLength(e.value)+2});oE.ISSUER_CRITICAL=128;const sE=Kv({encode(e,t,r){t||(t=new Uint8Array(sE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Vv(t,e.preference||0,r),r+=2,Gv.encode(e.exchange,t,r),r+=Gv.encode.bytes,Vv(t,r-n-2,n),sE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=Hv(e,t),t+=2,n.exchange=Gv.decode(e,t),t+=Gv.decode.bytes,sE.decode.bytes=t-r,n},encodingLength:e=>4+Gv.encodingLength(e.exchange)}),iE=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(iE.encodingLength(e))),r||(r=0),Vv(t,4,r),r+=2,wv.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,wv.decode(e,t)),bytes:6}),aE=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(aE.encodingLength(e))),r||(r=0),Vv(t,16,r),r+=2,vv.encode(e,t,r),aE.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=vv.decode(e,t);return aE.decode.bytes=18,r},bytes:18}),cE=e=>new Uint8Array(e),lE=Kv({encode(e,t,r){t||(t=new Uint8Array(lE.encodingLength(e))),r||(r=0);const n=r,o=Tv(e.code);if(Vv(t,o,r),r+=2,e.data)Vv(t,e.data.length,r),r+=2,zv(e.data,t,r),r+=e.data.length;else switch(o){case 8:{const n=e.sourcePrefixLength||0,o=e.family||function(e){return Ev(e)===wv.size?1:2}(e.ip),s=function(e,t,r){r=~~r;const n=Ev(e);return"function"==typeof t&&(t=t(r+n)),n===wv.size?wv.encode(e,t,r):vv.encode(e,t,r)}(e.ip,cE),i=Math.ceil(n/8);Vv(t,i+4,r),Vv(t,o,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,zv(s,t,r,0,i),r+=i}break;case 11:e.timeout?(Vv(t,2,r),r+=2,Vv(t,e.timeout,r),r+=2):(Vv(t,0,r),r+=2);break;case 12:{const n=e.length||0;Vv(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;Vv(t,n,r),r+=2;for(const n of e.tags)Vv(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return lE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=Hv(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);const n=Hv(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=Hv(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const o=new Uint8Array(1===r.family?4:16);zv(e,o,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===wv.size)return wv.decode(e,t,r);if(r===vv.size)return vv.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${wv.size} for v4 or ${vv.size} for v6.`)}(o)}break;case 11:n>0&&(r.timeout=Hv(e,t),t+=2);break;case 14:r.tags=[];for(let o=0;o<n;o+=2)r.tags.push(Hv(e,t)),t+=2}return lE.decode.bytes=n+4,r},encodingLength(e){if(e.data)return e.data.length+4;switch(Tv(e.code)){case 8:{const t=e.sourcePrefixLength||0;return Math.ceil(t/8)+8}case 11:return"number"==typeof e.timeout?6:4;case 12:return e.length+4;case 14:return 4+2*e.tags.length}throw new Error(`Unknown roption code: ${e.code}`)}}),uE=Kv({encode(e,t,r){t||(t=new Uint8Array(uE.encodingLength(e))),r||(r=0);const n=r,o=TE(e,lE);return Vv(t,o,r),r=_E(e,lE,t,r+2),uE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n=[];let o=Hv(e,t);t+=2;let s=0;for(;o>0;)n[s++]=lE.decode(e,t),t+=lE.decode.bytes,o-=lE.decode.bytes;return uE.decode.bytes=t-r,n},encodingLength:e=>2+TE(e||[],lE)}),hE=Kv({encode(e,t,r){t||(t=new Uint8Array(hE.encodingLength(e))),r||(r=0);const n=r,o=e.key;if(!Ov(o))throw new Error("Key must be a Buffer");return r+=2,Vv(t,e.flags,r),t[r+=2]=hE.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,zv(o,t,r+=1,0,o.length),r+=o.length,hE.encode.bytes=r-n,Vv(t,hE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);if(t+=2,n.flags=Hv(e,t),e[t+=2]!==hE.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+o+2),t+=n.key.length,hE.decode.bytes=t-r,n},encodingLength:e=>6+Rv(e.key)});hE.PROTOCOL_DNSSEC=3,hE.ZONE_KEY=128,hE.SECURE_ENTRYPOINT=32768;const dE=Kv({encode(e,t,r){t||(t=new Uint8Array(dE.encodingLength(e))),r||(r=0);const n=r,o=e.signature;if(!Ov(o))throw new Error("Signature must be a Buffer");return r+=2,Vv(t,Av(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,jv(t,e.originalTTL,r),r+=4,jv(t,e.expiration,r),r+=4,jv(t,e.inception,r),r+=4,Vv(t,e.keyTag,r),r+=2,Gv.encode(e.signersName,t,r),zv(o,t,r+=Gv.encode.bytes,0,o.length),r+=o.length,dE.encode.bytes=r-n,Vv(t,dE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);return t+=2,n.typeCovered=Sv(Hv(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=qv(e,t),t+=4,n.expiration=qv(e,t),t+=4,n.inception=qv(e,t),t+=4,n.keyTag=Hv(e,t),t+=2,n.signersName=Gv.decode(e,t),t+=Gv.decode.bytes,n.signature=e.slice(t,r+o+2),t+=n.signature.length,dE.decode.bytes=t-r,n},encodingLength:e=>20+Gv.encodingLength(e.signersName)+Rv(e.signature)}),pE=Kv({encode(e,t,r){t||(t=new Uint8Array(pE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Gv.encode(e.mbox||".",t,r),r+=Gv.encode.bytes,Gv.encode(e.txt||".",t,r),r+=Gv.encode.bytes,pE.encode.bytes=r-n,Vv(t,pE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=Gv.decode(e,t)||".",t+=Gv.decode.bytes,n.txt=Gv.decode(e,t)||".",t+=Gv.decode.bytes,pE.decode.bytes=t-r,n},encodingLength:e=>2+Gv.encodingLength(e.mbox||".")+Gv.encodingLength(e.txt||".")}),fE=Kv({encode(e,t,r){t||(t=new Uint8Array(fE.encodingLength(e))),r||(r=0);const n=r,o=[];for(let t=0;t<e.length;t++){const r=Av(e[t]);void 0===o[r>>8]&&(o[r>>8]=[]),o[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e<o.length;e++)if(void 0!==o[e]){const n=Dv(o[e]);t[r]=e,t[r+=1]=n.length,zv(n,t,r+=1,0,n.length),r+=n.length}return fE.encode.bytes=r-n,t},decode(e,t,r){t||(t=0);const n=t,o=[];for(;t-n<r;){const r=e[t],n=e[t+=1];t+=1;for(let s=0;s<n;s++){const n=e[t+s];for(let e=0;e<8;e++)if(n&1<<7-e){const t=Sv(r<<8|s<<3|e);o.push(t)}}t+=n}return fE.decode.bytes=t-n,o},encodingLength(e){const t=[];for(let r=0;r<e.length;r++){const n=Av(e[r]);t[n>>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e<t.length;e++)void 0!==t[e]&&(r+=2+Math.ceil((t[e]+1)/8));return r}}),gE=Kv({encode(e,t,r){t||(t=new Uint8Array(gE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Gv.encode(e.nextDomain,t,r),r+=Gv.encode.bytes,fE.encode(e.rrtypes,t,r),r+=fE.encode.bytes,gE.encode.bytes=r-n,Vv(t,gE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);return t+=2,n.nextDomain=Gv.decode(e,t),t+=Gv.decode.bytes,n.rrtypes=fE.decode(e,t,o-(t-r)),t+=fE.decode.bytes,gE.decode.bytes=t-r,n},encodingLength:e=>2+Gv.encodingLength(e.nextDomain)+fE.encodingLength(e.rrtypes)}),mE=Kv({encode(e,t,r){t||(t=new Uint8Array(mE.encodingLength(e))),r||(r=0);const n=r,o=e.salt;if(!Ov(o))throw new Error("salt must be a Buffer");const s=e.nextDomain;if(!Ov(s))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,Vv(t,e.iterations,r),t[r+=2]=o.length,zv(o,t,r+=1,0,o.length),t[r+=o.length]=s.length,zv(s,t,r+=1,0,s.length),r+=s.length,fE.encode(e.rrtypes,t,r),r+=fE.encode.bytes,mE.encode.bytes=r-n,Vv(t,mE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=Hv(e,t);const s=e[t+=2];t+=1,n.salt=e.slice(t,t+s);const i=e[t+=s];return t+=1,n.nextDomain=e.slice(t,t+i),t+=i,n.rrtypes=fE.decode(e,t,o-(t-r)),t+=fE.decode.bytes,mE.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+fE.encodingLength(e.rrtypes)}),yE=Kv({encode(e,t,r){t||(t=new Uint8Array(yE.encodingLength(e))),r||(r=0);const n=r,o=e.digest;if(!Ov(o))throw new Error("Digest must be a Buffer");return r+=2,Vv(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,zv(o,t,r+=1,0,o.length),r+=o.length,yE.encode.bytes=r-n,Vv(t,yE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);return t+=2,n.keyTag=Hv(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+o+2),t+=n.digest.length,yE.decode.bytes=t-r,n},encodingLength:e=>6+Rv(e.digest)});function bE(e){switch(e.toUpperCase()){case"A":return iE;case"PTR":case"CNAME":case"DNAME":return rE;case"TXT":return Qv;case"NULL":return eE;case"AAAA":return aE;case"SRV":return nE;case"HINFO":return tE;case"CAA":return oE;case"NS":return Yv;case"SOA":return Zv;case"MX":return sE;case"OPT":return uE;case"DNSKEY":return hE;case"RRSIG":return dE;case"RP":return pE;case"NSEC":return gE;case"NSEC3":return mE;case"DS":return yE}return Xv}const wE=Kv({encode(e,t,r){t||(t=new Uint8Array(wE.encodingLength(e))),r||(r=0);const n=r;if(Gv.encode(e.name,t,r),r+=Gv.encode.bytes,Vv(t,Av(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");Vv(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,Vv(t,e.flags||0,r+6),r+=8,uE.encode(e.options||[],t,r),r+=uE.encode.bytes}else{let n=xv(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),Vv(t,n,r+2),jv(t,e.ttl||0,r+4),r+=8;const o=bE(e.type);o.encode(e.data,t,r),r+=o.encode.bytes}return wE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=Gv.decode(e,t),t+=Gv.decode.bytes,r.type=Sv(Hv(e,t)),"OPT"===r.type)r.udpPayloadSize=Hv(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=Hv(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=uE.decode(e,t+8),t+=8+uE.decode.bytes;else{const n=Hv(e,t+2);r.ttl=qv(e,t+4),r.class=Iv(-32769&n),r.flush=!!(32768&n);const o=bE(r.type);r.data=o.decode(e,t+8),t+=8+o.decode.bytes}return wE.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return Gv.encodingLength(e.name)+8+bE(e.type).encodingLength(t)}}),vE=Kv({encode(e,t,r){t||(t=new Uint8Array(vE.encodingLength(e))),r||(r=0);const n=r;return Gv.encode(e.name,t,r),r+=Gv.encode.bytes,Vv(t,Av(e.type),r),r+=2,Vv(t,xv(void 0===e.class?"IN":e.class),r),r+=2,vE.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=Gv.decode(e,t),t+=Gv.decode.bytes,n.type=Sv(Hv(e,t)),t+=2,n.class=Iv(Hv(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),vE.decode.bytes=t-r,n},encodingLength:e=>Gv.encodingLength(e.name)+4}),EE={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(xE(e))),r||(r=0);const o=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),Jv.encode(e,t,r),r+=Jv.encode.bytes,r=_E(e.questions,vE,t,r),r=_E(e.answers,wE,t,r),r=_E(e.authorities,wE,t,r),r=_E(e.additionals,wE,t,r),EE.encode.bytes=r-o,n&&CE.bytes!==t.length?t.slice(0,CE.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=Jv.decode(e,t);return t+=Jv.decode.bytes,t=NE(n.questions,vE,e,t),t=NE(n.answers,wE,e,t),t=NE(n.authorities,wE,e,t),t=NE(n.additionals,wE,e,t),EE.decode.bytes=t-r,n},encodingLength:function(e){return Jv.encodingLength(e)+TE(e.questions||[],vE)+TE(e.answers||[],wE)+TE(e.authorities||[],wE)+TE(e.additionals||[],wE)}};function SE(e,t){if(e.questions)throw new Error("Only one .question object expected instead of a .questions array!");const r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}EE.encode.bytes=0,EE.decode.bytes=0;const AE={encode:function(e,t,r){return t=EE.encode(SE(e,"query"),t,r),AE.encode.bytes=EE.encode.bytes,t},decode:function(e,t){const r=EE.decode(e,t);return AE.decode.bytes=EE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return EE.encodingLength(SE(e,"query"))}};AE.encode.bytes=0,AE.decode.bytes=0;const kE={encode:function(e,t,r){return t=EE.encode(SE(e,"response"),t,r),kE.encode.bytes=EE.encode.bytes,t},decode:function(e,t){const r=EE.decode(e,t);return kE.decode.bytes=EE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return EE.encodingLength(SE(e,"response"))}};kE.encode.bytes=0,kE.decode.bytes=0;const CE=EE.encode,IE=EE.decode,xE=EE.encodingLength;function TE(e,t){let r=0;for(let n=0;n<e.length;n++)r+=t.encodingLength(e[n]);return r}function _E(e,t,r,n){for(let o=0;o<e.length;o++)t.encode(e[o],r,n),n+=t.encode.bytes;return n}function NE(e,t,r,n){for(let o=0;o<e.length;o++)e[o]=t.decode(r,n),n+=t.decode.bytes;return n}function PE(e,t,r,n){if(64!==t.length)throw new Error(`Charset needs to be 64 characters long! (${t.length})`);const o=new Uint8Array(256),s=new Uint8Array(64);for(let e=0;e<64;e+=1){const r=t.charCodeAt(e);if(r>255)throw new Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==o[r])throw new Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);o[r]=e,s[e]=r}const i=r.charCodeAt(0),a={name:e,encodingLength(e){const t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===i?e.charCodeAt(t-2)===i?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)===i&&(e.charCodeAt(n-2)===i?n-=2:n-=1);const s=n%4,c=n-s;let l=r,u=0;for(;u<c;){const r=o[e.charCodeAt(u)]<<18|o[e.charCodeAt(u+1)]<<12|o[e.charCodeAt(u+2)]<<6|o[e.charCodeAt(u+3)];t[l++]=r>>16,t[l++]=r>>8,t[l++]=r,u+=4}if(3===s){const r=o[e.charCodeAt(u)]<<10|o[e.charCodeAt(u+1)]<<4|o[e.charCodeAt(u+2)]>>2;t[l++]=r>>8,t[l++]=r}else 2===s&&(t[l++]=o[e.charCodeAt(u)]<<2|o[e.charCodeAt(u+1)]>>4);return a.encode.bytes=l-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);const o=r-t,c=o%3,l=t+o-c,u=[];for(let r=t;r<l;r+=3){const t=e[r]<<16|e[r+1]<<8|e[r+2];u.push(s[t>>18&63],s[t>>12&63],s[t>>6&63],s[63&t])}if(2===c){const 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(i)}else if(1===c){const t=e[r-1];u.push(s[t>>2],s[t<<4&63]),1===n&&u.push(i,i)}return a.decode.bytes=o,String.fromCharCode.apply(String,u)}};return a}PE("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const LE=PE("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let BE="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;BE||(BE=class extends Error{constructor(e="Request aborted."){super(e)}}),BE.prototype.name="AbortError",BE.prototype.code="ABORT_ERR";const OE="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class RE 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}}}RE.prototype.name="HTTPStatusError",RE.prototype.code="HTTP_STATUS";class DE extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:$E(this.cause)}}}DE.prototype.name="ResponseError",DE.prototype.code="RESPONSE_ERR";class UE extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}UE.prototype.name="TimeoutError",UE.prototype.code="ETIMEOUT";const ME=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,FE=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function $E(e){if("string"==typeof e)return{message:e};try{const t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}const t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}const qE=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,HE=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,jE=/\[(((pk|name)=([^\]]+)))\]/gi;function VE(e,t){t.lastIndex=0;const r={};for(;;){const n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class zE extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${KE.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}zE.prototype.name="InvalidProtocolError",zE.prototype.code="EPROTOCOL";const KE=["http:","https:","udp4:","udp6:"];class GE{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;const 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))throw new Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`);this.port=r}}toJSON(){return this.toString()}}class WE extends GE{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){const 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 JE extends WE{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw new Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class XE extends WE{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw new Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function YE(e){return FE.test(e)&&!ME.test(e)?`[${e}]`:e}class ZE extends GE{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 new 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){const e=FE.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||ME.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${YE(this.host)}:${this.port}${this.path}`;try{this.url=new OE(t)}catch(e){throw new Error(e.message+` [${t}]`)}}toString(){const 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,o=this.name?` [name=${this.name}]`:"",s=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",i=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${YE(this.host)}${t}${n}${r}${s}${i}${o}`}}function QE(e){let t;if("string"==typeof e)t=function(e){const t=qE.exec(e),r=t[2]||"https:",n=t[3],o=t[5],s=t[6],i=t[7];if("https:"===r||"http:"===r){const e=VE(i,HE);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:o,path:s,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=VE(i,jE),s=/^\[(.*)\]$/.exec(n);if(s&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!s&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return s?new XE({protocol:"udp6:",ipv6:s[1],port:o,pk:t.pk,name:t.name}):new JE({protocol:"udp4:",ipv4:n,port:o,pk:t.pk,name:t.name})}throw new zE(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Can not convert ${e} to an endpoint`);if(e instanceof GE)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new JE(t);if("udp6:"===r)return new XE(t);if("https:"===r||"http:"===r)return new ZE(t);throw new zE(r,JSON.stringify(t))}const eS="application/dns-message";function tS(){}function rS(e,t,r,n,o){return new Promise(((s,i)=>{const a=new OE(e);"GET"===t&&r&&(a.search="?dns="+LE.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",eS),"POST"===t&&l.setRequestHeader("Content-Type",eS),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new UE(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new RE(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new RE(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new RE(c,l.status,t));else{let e;if("string"==typeof l.response)e=Lv(l.response);else if(l.response instanceof Uint8Array)e=l.response;else{if(!(Array.isArray(l.response)||l.response instanceof ArrayBuffer))throw new Error("Unprocessable response "+l.response);e=new Uint8Array(l.response)}u(null,e)}},"POST"===t?l.send(r):l.send(),o&&o.addEventListener("abort",h);let u=function(e,t){u=tS,o&&o.removeEventListener("abort",h),s(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new BE);try{l.abort()}catch(e){}}}))}function nS(e){const t=null===e.time||void 0===e.time?Date.now():e.time,r=function(e){return e.filter((e=>e.cors||e.endpoint.cors))}(e.data.map((e=>(e.endpoint=QE(Object.assign({name:e.name},e.endpoint)),e)))),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}}Error;const oS=nS({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});const sS=new OE("https://martinheidegger.github.io/dns-query/resolvers.json");function iS(e){return/^@/.test(e)}const aS=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:sS,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?async function(e,t,r){const n=t?t.localStoragePrefix+t.name:null;if(n)try{const e=JSON.parse(localStorage.getItem(n));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:o}=await rS(e,"GET",null,r,void 0),s={time:Date.now(),data:JSON.parse(Bv(o))};if(n)try{localStorage.setItem(n,JSON.stringify(s))}catch(e){s.time=null}return s}(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=>nS({data:e.data.resolvers,time:e.time}))).catch((()=>t||oS)):Promise.resolve(oS),this._dataP):this._dataP.then((e=>e.time<Date.now()-this.opts.maxAge?this._data(!0,e):e))}data(){return this._data(!1).then((e=>e.data))}endpoints(e){if(null==e)return this.data().then((e=>e.endpoints));if("doh"===e&&(e=uS),"dns"===e&&(e=hS),"function"==typeof e)return this.data().then((t=>t.endpoints.filter(e)));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(iS))try{return Promise.resolve(e.map(QE))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(iS(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return QE(e)}))))}};function cS(e,t){return t=Object.assign({retries:5,timeout:3e4},t),e.question?(r=t.endpoints,function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(r)?r:Promise.resolve(r)).then((r=>{if(!Array.isArray(r)||0===r.length)throw new Error("No endpoints defined to lookup dns records.");return lS(r.map(QE),function(e){const t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(e),t)})).then((e=>(e.question=e.questions[0],delete e.questions,e))):Promise.reject(new Error("To request data you need to specify a .question!"));var r}function lS(e,t,r){const n=1===e.length?e[0]:e[Math.floor(Math.random()*e.length)%e.length];return function(e,t,r,n){return n&&n.aborted?Promise.reject(new BE):"udp4:"===e.protocol||"udp6:"===e.protocol?function(){throw new Error('Only "doh" endpoints are supported in the browser')}():function(e,t,r,n){return function(e,t,r,n,o){return rS(e,t,r,n,o)}(e.url,e.method,CE(Object.assign({flags:256},t)),r,n).then((function(e){const t=e.data,r=e.response;let n=e.error;if(void 0===n)if(0===t.length)n=new DE("Empty.");else try{const e=IE(t);return e.response=r,e}catch(e){n=new DE("Invalid packet (cause="+e.message+")",e)}throw Object.assign(n,{response:r})}))}(e,t,r,n)}(n,t,r.timeout,r.signal).then((e=>(e.endpoint=n.toString(),e)),(o=>{if("AbortError"===o.name||0===r.retries)throw o.endpoint=n.toString(),o;return r.retries>0&&(r.retries-=1),lS(e,t,r)}))}function uS(e){return"https:"===e.protocol||"http:"===e.protocol}function hS(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const dS=new gn("dns-over-https");class pS{endpoints;retries;static async create(e,t){const r=e??await aS.endpoints("doh");return new pS(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await cS({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw dS.error("query failed: ",e),new Error("DNS query failed")}if(!t)throw new Error(`Could not resolve ${e}`);const r=t.map((e=>e.data)),n=[];return r.forEach((e=>{"string"==typeof e?n.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?n.push(e):n.push(tn(e))})):n.push(tn(e))})),n}}var fS=__webpack_require__(5818);class gS{static RECORD_PREFIX=jw.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 new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=gS.parseRootValues(e),n=fS.decode.asBytes(t),o=e.split(" sig")[0],s=rn(o);if(!Tw(xt(r.signature,"base64url").slice(0,64),xw(s),new Uint8Array(n)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree root entry");t.shift();const[r,n,o,s]=t;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!o)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(o),signature:s}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!n)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const mS=new gn("discovery:fetch_nodes");function yS(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function bS(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function wS(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function vS(e,t,r){if(yS(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relay<e.relay,store:t.store<e.store,filter:t.filter<e.filter,lightPush:t.lightPush<e.lightPush}}(t,r);return n.relay&&e.relay||n.store&&e.store||n.filter&&e.filter||n.lightPush&&e.lightPush}const ES=new gn("discovery:dns");class SS{dns;_DNSTreeCache;_errorTolerance=10;static async dnsOverHttp(e){return e||(e=await pS.create()),new SS(e)}async getPeers(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:o}=gS.parseTree(e[r]),s={domain:o,publicKey:n,visits:{}},i=await async function(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},o=n.relay+n.store+n.filter+n.lightPush,s={relay:0,store:0,filter:0,lightPush:0};let i=0;const a=[];for(;!yS(n,s)&&i<o+t;){const e=await r();e&&bS(e,a)&&(e.waku2&&vS(e.waku2,n,s)&&(wS(e.waku2,s),a.push(e)),mS.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),i++}return a}(t,this._errorTolerance,(()=>this._search(o,s)));return ES.info("retrieved peers: ",i.map((e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map((e=>e.toString()))})))),i}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:o}=gS.parseTree(e[r]),s={domain:o,publicKey:n,visits:{}};for await(const e of async function*(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},o=n.relay+n.store+n.filter+n.lightPush,s={relay:0,store:0,filter:0,lightPush:0};let i=0;const a=new Set;for(;!yS(n,s)&&i<o+t;){const e=await r();e&&e.nodeId&&!a.has(e.nodeId)&&(a.add(e.nodeId),e.waku2&&vS(e.waku2,n,s)&&(wS(e.waku2,s),yield e),mS.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),i++}}(t,this._errorTolerance,(()=>this._search(o,s))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,o;t.visits[e]=!0;const s=function(e){return e.startsWith(gS.ROOT_PREFIX)?gS.ROOT_PREFIX:e.startsWith(gS.BRANCH_PREFIX)?gS.BRANCH_PREFIX:e.startsWith(gS.RECORD_PREFIX)?gS.RECORD_PREFIX:""}(r);try{switch(s){case gS.ROOT_PREFIX:return n=gS.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case gS.BRANCH_PREFIX:return o=gS.parseBranch(r),n=function(e,t){const r={};for(const[n,o]of e.entries())t.visits[o]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw new Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(o,t),await this._search(n,t);case gS.RECORD_PREFIX:return mv.fromString(r);default:return null}}catch(t){return ES.error(`Failed to search DNS tree ${s} at subdomain ${e}: ${t}`),null}}catch(t){return ES.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw new Error("Received empty result array while fetching TXT record");if(!n[0].length)throw new Error("Received empty TXT record");const o=n.join("");return this._DNSTreeCache[e]=o,o}}const AS=new gn("peer-discovery-dns");class kS extends xo{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;AS.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){AS.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await SS.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[Ib]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let o=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(Ib)||(o=!0,await this._components.peerStore.merge(t.id,{tags:n})):(o=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:dn(r)}}})),o&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[Ad](){return!0}get[Symbol.toStringTag](){return Jr}}function CS(e,t=xb){return r=>new kS(r,{enrUrls:e,wantedNodeCapabilityCount:t})}function IS(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const xS="consumed";class TS{multicodec;getConnections;addEventListener;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new gn(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e.id);return n?(this.log.info(`Found existing stream peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.lockStream(e.id.toString(),n),n):(n=await this.createStream(e),this.lockStream(e.id.toString(),n),n)}async createStream(e,t=0){const r=IS(this.getConnections(e.id));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.id.toString()} multicodec=${this.multicodec}`);let n,o;for(let s=0;s<t+1;s++)try{this.log.info(`Attempting to create a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),o=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(!o)throw new Error(`Failed to create a new stream for ${e.id.toString()} -- `+n);return o}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=IS(this.getConnections(e));if(!t)return;const r=t.streams.find((e=>e.protocol===this.multicodec));return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[xS]=!0}isStreamLocked(e){return!!e.metadata[xS]}}class _S{multicodec;components;pubsubTopics;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r){this.multicodec=e,this.components=t,this.pubsubTopics=r,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new TS(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}}class NS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new NS({query:{numPeers:t},response:void 0})}encode(){return gr.encode(this.proto)}static decode(e){const t=gr.decode(e);return new NS(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const PS="/vac/waku/peer-exchange/2.0.0-alpha1",LS=new gn("peer-exchange");class BS extends _S{constructor(e,t){super(PS,e,t)}async query(e){const{numPeers:t,peerId:r}=e,n=NS.createRequest({numPeers:BigInt(t)}),o=await this.components.peerStore.get(r);if(!o)return{peerInfos:null,error:zr.NO_PEER_AVAILABLE};let s;try{s=await this.getStream(o)}catch(e){return LS.error("Failed to get stream",e),{peerInfos:null,error:zr.NO_STREAM_AVAILABLE}}const i=await Kn([n.encode()],Ln,s,Fn,(async e=>await An(e)));try{const e=new _n;i.forEach((t=>{e.append(t)}));const{response:t}=NS.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Ar).map((async e=>({ENR:await mv.fromRLP(e)})))),error:null}:(LS.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:zr.EMPTY_PAYLOAD})}catch(e){return LS.error("Failed to decode push reply",e),{peerInfos:null,error:zr.DECODE_FAILED}}}}const OS=new gn("peer-exchange-discovery"),RS=1e4,DS=3,US=Kr.PEER_EXCHANGE;class MS extends xo{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(PS)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>OS.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new BS(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(this.dispatchEvent(new CustomEvent("waku:peer-exchange:started",{detail:!0})),OS.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(OS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[Ad](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=RS,maxRetries:n=DS}=this.options;OS.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const o=this.queryAttempts.get(t)??1;o>n?this.abortQueriesForPeer(t):setTimeout((()=>{this.queryAttempts.set(t,o+1),this.startRecurringQueries(e).catch((e=>{OS.error(`Error in startRecurringQueries: ${e}`)}))}),r*o)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return OS.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){OS.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:o}=t;if(r&&n){if(await this.components.peerStore.has(r)){const{hasMultiaddrDiff:e,hasShardDiff:t}=await this.checkPeerInfoDiff(n,o);if(e||t){OS.info(`Peer ${r.toString()} has updated multiaddrs or shardInfo, updating`),e&&(OS.info(`Peer ${r.toString()} has updated multiaddrs, updating`),await this.components.peerStore.patch(r,{multiaddrs:n.multiaddrs})),t&&o&&(OS.info(`Peer ${r.toString()} has updated shardInfo, updating`),await this.components.peerStore.merge(r,{metadata:{shardInfo:dn(o)}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})));continue}}await this.components.peerStore.save(r,{tags:{[US]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...o&&{metadata:{shardInfo:dn(o)}},...n.multiaddrs&&{multiaddrs:n.multiaddrs}}),OS.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))}}return{error:null,peerInfos:r}}abortQueriesForPeer(e){OS.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}async checkPeerInfoDiff(e,t){const{id:r}=e,n=await this.components.peerStore.get(r),o=n.addresses.map((e=>e.multiaddr.toString())),s=e.multiaddrs.map((e=>e.toString())),i=o.some((e=>!s.includes(e)));let a=!1;const c=n.metadata.get("shardInfo");if(c){const e=hn(c);(e||t)&&(a=e.clusterId!==t?.clusterId||e.shards.some((e=>!t?.shards.includes(e))))}return{hasMultiaddrDiff:i,hasShardDiff:a}}}function FS(e){return t=>new MS(t,e)}const $S=new gn("peer-exchange-discovery"),qS=Kr.LOCAL;class HS extends xo{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){$S.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=nh(e);await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[Is(t)],tags:{[this.options?.tagName??qS]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:[Is(t)]}})))}$S.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&($S.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=function(e){const t=e.find((e=>e.toString().includes("ws")||e.toString().includes("wss")));if(!t)throw new Error("No ws multiaddr found in the given addresses");return t}(r),o=this.getPeersFromLocalStorage(),s=o.findIndex((e=>e.id===t.toString()));s>=0?o[s].address=n.toString():o.push({id:t.toString(),address:n.toString()}),this.peers=o,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(jS):[]}catch(e){return $S.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){$S.error("Error saving peers to local storage:",e)}}}function jS(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const VS=new gn("sdk:create");async function zS(e,t,r){t?.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"));const n=e?{metadata:Mo(e)}:{};return async function(e={}){e.privateKey??=await zu("Ed25519");const t=new Cb({...await Mg(e),peerId:(r=e.privateKey,oh(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[yg({filter:!1===t?.filterMultiaddrs?fg:gg})],streamMuxers:[Gf()],connectionEncrypters:[Sd()],...t,services:{identify:vf({agentVersion:r??"js-waku"}),ping:Xf({maxInboundStreams:t?.pingMaxInboundStreams??10}),...n,...t?.services}})}async function KS(e={}){const{libp2p:t,pubsubTopics:r}=await async function(e){const{networkConfig:t}=e,r=function(e){if("clusterId"in(t=e)&&"shards"in t&&!("contentTopics"in t)){if(0===e.shards.length)throw new Error("Invalid shards configuration: please provide at least one shard");return on(e)}if(function(e){return"contentTopics"in e}(e)){if(0===e.contentTopics.length)throw new Error("Invalid content topics configuration: please provide at least one content topic");return e.contentTopics.map((t=>ln(t,e.clusterId)))}throw new Error("Unknown shard config. Please use ShardInfo or ContentTopicInfo");var t}(t??Xr);VS.info("Creating Waku node with pubsub topics",r);const n=e?.libp2p??{},o=n.peerDiscovery??[];var s;return e?.defaultBootstrap&&o.push(...function(e){return[CS(["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im","enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"]),(e,t)=>new HS(e,t),FS(e)]}(r)),e?.bootstrapPeers&&o.push((s={list:e.bootstrapPeers},e=>new rp(e,s))),n.peerDiscovery=o,{libp2p:await zS(r,n,e?.userAgent),pubsubTopics:r}}(e);return new zs(r,e,t,{store:!0,lightpush:!0,filter:!0})}var GS,WS=__webpack_require__(2549),JS=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},XS=function(e,t){var r,n,o,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}};!function(e){e.LIGHT_PUSH_FILTER="LightPushFilter"}(GS||(GS={}));var YS=function(){function e(e,t){void 0===t&&(t=5e3),this.url=e,this.intervalPeriod=t,this.queue=[],this.intervalId=null,this.requestId=0}return e.prototype.push=function(e){var t;(t=this.queue).push.apply(t,e)},e.prototype.start=function(){return JS(this,void 0,void 0,(function(){var e=this;return XS(this,(function(t){return this.intervalId||(this.intervalId=setInterval((function(){return JS(e,void 0,void 0,(function(){return XS(this,(function(e){switch(e.label){case 0:return this.queue.length>0?[4,this.send(this.queue)]:[3,2];case 1:e.sent()&&(console.log("Sent ",this.queue.length," telemetry logs"),this.queue=[]),e.label=2;case 2:return[2]}}))}))}),this.intervalPeriod)),[2]}))}))},e.prototype.stop=function(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)},e.prototype.send=function(e){return JS(this,void 0,void 0,(function(){var t,r,n,o=this;return XS(this,(function(s){switch(s.label){case 0:if(!window.location.hostname.includes("lab.waku.org"))return[2];t=e.map((function(e){return{id:++o.requestId,telemetryType:e.type.toString(),telemetryData:e}})),s.label=1;case 1:return s.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=s.sent()).status?(console.log("DEBUG: Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=s.sent(),console.log("DEBUG: Error sending messages to telemetry service",n),[2,!1];case 4:return[2]}}))}))},e}(),ZS=function(){return ZS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},ZS.apply(this,arguments)},QS=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},eA=function(e,t){var r,n,o,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},tA=function(){return Math.floor(1e6*Math.random())},rA=function(e){return QS(void 0,void 0,void 0,(function(){var t,r,n;return eA(this,(function(o){switch(o.label){case 0:return t=new TextEncoder,r=t.encode(e.toString()),[4,crypto.subtle.digest("SHA-256",r)];case 1:return n=o.sent(),[2,Array.from(new Uint8Array(n)).map((function(e){return e.toString(16).padStart(2,"0")})).join("")]}}))}))},nA={sdk:"0.0.29-rc"},oA=(JSON.stringify(nA),function(e,t){return QS(void 0,void 0,void 0,(function(){var r,n,o;return eA(this,(function(s){switch(s.label){case 0:return r=ZS({},nA),[4,e.libp2p.peerStore.all()];case 1:return(n=s.sent().find((function(e){return e.id.toString()===t})))&&t!==e.libp2p.peerId.toString()?(o=n.addresses.map((function(e){return e.multiaddr.toString()})).some((function(e){return e.includes("ws")||e.includes("wss")})),[2,JSON.stringify(ZS(ZS({},r),{peerId:t,websocket:o,enabledProtocols:n.protocols}))]):[2,JSON.stringify(r)]}}))}))}),sA=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},iA=function(e,t){var r,n,o,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},aA="/js-waku-examples/1/message-ratio/utf8",cA=ln(aA),lA=new WS.Type("SequencedMessage").add(new WS.Field("hash",1,"string")).add(new WS.Field("total",2,"uint64")).add(new WS.Field("index",3,"uint64")).add(new WS.Field("sender",4,"string")),uA=new CustomEvent("sequenceCompleted"),hA=(new CustomEvent("messageSent"),new CustomEvent("messageReceived"));function dA(){return sA(this,void 0,void 0,(function(){var e,t;return iA(this,(function(r){switch(r.label){case 0:return(e=localStorage.getItem("seed"))?[3,2]:[4,rA(tA())];case 1:e=r.sent().slice(0,32),localStorage.setItem("seed",e),r.label=2;case 2:return[4,Ku("Ed25519",xt(e))];case 3:return t=r.sent(),[2,KS({networkConfig:{contentTopics:[aA]},numPeersToUse:2,defaultBootstrap:!0,libp2p:{privateKey:t}})]}}))}))}function pA(e){return sA(this,void 0,void 0,(function(){var t,r,n,o,s,i=this;return iA(this,(function(a){switch(a.label){case 0:return[4,dA()];case 1:return t=a.sent(),window.waku=t,console.log("DEBUG: your peer ID is:",t.libp2p.peerId.toString()),[4,t.start()];case 2:return a.sent(),[4,t.waitForPeers()];case 3:return a.sent(),r=t.libp2p.peerId.toString(),n=vn({contentTopic:aA}),t.libp2p.addEventListener("peer:discovery",(function(n){return sA(i,void 0,void 0,(function(){var o,s,i,a;return iA(this,(function(c){switch(c.label){case 0:return o=n.detail.id.toString(),s=Math.floor((new Date).getTime()/1e3),[4,oA(t,o)];case 1:return i=c.sent(),[4,rA("".concat(r,"-").concat(o,"-").concat(s))];case 2:return a=c.sent(),e.push([{type:GS.LIGHT_PUSH_FILTER,protocol:"discovery",timestamp:s,createdAt:s,seenTimestamp:s,peerId:r,contentTopic:aA,pubsubTopic:cA,ephemeral:!1,messageHash:a,errorMessage:"",extraData:i}]),[2]}}))}))})),o=function(e){for(var o=[],s=1;s<arguments.length;s++)o[s-1]=arguments[s];return sA(i,function(e,t,r){if(r||2===arguments.length)for(var n,o=0,s=t.length;o<s;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([e],o,!0),void 0,(function(e,o){var s,i,a,c,l=this;return void 0===o&&(o=3e3),iA(this,(function(u){switch(u.label){case 0:return[4,rA(tA())];case 1:return s=u.sent(),i=e,a=0,c=function(){return sA(l,void 0,void 0,(function(){var e,l,u,h,d;return iA(this,(function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),[4,rA("".concat(s,"-").concat(a,"-").concat(i))];case 1:return e=p.sent(),Math.floor((new Date).getTime()/1e3),l=lA.create({hash:e,total:i,index:a,sender:r}),u=lA.encode(l).finish(),[4,t.lightPush.send(n,{payload:u,timestamp:new Date},{autoRetry:!0})];case 2:return h=p.sent(),console.log("DEBUG: light push successes: ",h.successes.length),console.log("DEBUG: light push failures: ",h.failures.length),++a<i?setTimeout(c,o):document.dispatchEvent(uA),[3,4];case 3:return d=p.sent(),console.error("DEBUG: Error sending message",d),[3,4];case 4:return[2]}}))}))},c(),[2]}}))}))},s=function(){return sA(i,void 0,void 0,(function(){var e,n,o=this;return iA(this,(function(s){switch(s.label){case 0:return e=Sn(aA),n=function(e){return sA(o,void 0,void 0,(function(){var t;return iA(this,(function(n){return(t=lA.decode(e.payload)).sender===r||(Math.floor((new Date).getTime()/1e3),document.createElement("div").textContent="Message: ".concat(t.hash),document.dispatchEvent(hA)),[2]}))}))},[4,t.filter.subscribe(e,n)];case 1:return s.sent(),[2]}}))}))},[2,{node:t,startLightPushSequence:o,startFilterSubscription:s}]}}))}))}sA(void 0,void 0,void 0,(function(){var e,t;return iA(this,(function(r){switch(r.label){case 0:return[4,pA(new YS("https://telemetry.status.im/waku-metrics",5e3))];case 1:return(e=r.sent()).node,t=e.startLightPushSequence,(0,e.startFilterSubscription)(),document.addEventListener(uA.type,(function(){return t(10,3e3)})),t(10,3e3),[2]}}))}))})()})();
//# sourceMappingURL=index.js.map