(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () { "use strict";var Helia=(()=>{var DN=Object.create;var Oh=Object.defineProperty;var CN=Object.getOwnPropertyDescriptor;var PN=Object.getOwnPropertyNames;var kN=Object.getPrototypeOf,NN=Object.prototype.hasOwnProperty;var b6=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var et=(r,e)=>()=>(r&&(e=r(r=0)),e);var B=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),be=(r,e)=>{for(var t in e)Oh(r,t,{get:e[t],enumerable:!0})},w6=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of PN(e))!NN.call(r,i)&&i!==t&&Oh(r,i,{get:()=>e[i],enumerable:!(n=CN(e,i))||n.enumerable});return r};var j=(r,e,t)=>(t=r!=null?DN(kN(r)):{},w6(e||!r||!r.__esModule?Oh(t,"default",{value:r,enumerable:!0}):t,r)),Bh=r=>w6(Oh({},"__esModule",{value:!0}),r);var P2=B((UZ,E6)=>{var nc=1e3,ic=nc*60,sc=ic*60,ea=sc*24,ON=ea*7,BN=ea*365.25;E6.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return LN(r);if(t==="number"&&isFinite(r))return e.long?UN(r):MN(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function LN(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*BN;case"weeks":case"week":case"w":return t*ON;case"days":case"day":case"d":return t*ea;case"hours":case"hour":case"hrs":case"hr":case"h":return t*sc;case"minutes":case"minute":case"mins":case"min":case"m":return t*ic;case"seconds":case"second":case"secs":case"sec":case"s":return t*nc;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function MN(r){var e=Math.abs(r);return e>=ea?Math.round(r/ea)+"d":e>=sc?Math.round(r/sc)+"h":e>=ic?Math.round(r/ic)+"m":e>=nc?Math.round(r/nc)+"s":r+"ms"}function UN(r){var e=Math.abs(r);return e>=ea?Lh(r,e,ea,"day"):e>=sc?Lh(r,e,sc,"hour"):e>=ic?Lh(r,e,ic,"minute"):e>=nc?Lh(r,e,nc,"second"):r+" ms"}function Lh(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var v6=B((FZ,x6)=>{function FN(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=i,t.enabled=o,t.humanize=P2(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let h=0;h{if(v==="%%")return"%";_++;let T=t.formatters[R];if(typeof T=="function"){let P=g[_];v=T.call(y,P),g.splice(_,1),_--}return v}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(l,f){let h=t(this.namespace+(typeof f>"u"?":":f)+l);return h.log=this.log,h}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,h=(typeof l=="string"?l:"").split(/[\s,]+/),d=h.length;for(f=0;f"-"+f)].join(",");return t.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let f,h;for(f=0,h=t.skips.length;f{nn.formatArgs=VN;nn.save=qN;nn.load=zN;nn.useColors=KN;nn.storage=$N();nn.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();nn.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function KN(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function VN(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Mh.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}nn.log=console.debug||console.log||(()=>{});function qN(r){try{r?nn.storage.setItem("debug",r):nn.storage.removeItem("debug")}catch{}}function zN(){let r;try{r=nn.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function $N(){try{return localStorage}catch{}}Mh.exports=v6()(nn);var{formatters:HN}=Mh.exports;HN.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ac=B((ZZ,C6)=>{"use strict";function D6(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function uO(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return D6(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),D6(new i,t)}}C6.exports=uO});var i7=B((kte,n7)=>{n7.exports=r7;var t7=128,RB=127,IB=~RB,AB=Math.pow(2,31);function r7(r,e,t){e=e||[],t=t||0;for(var n=t;r>=AB;)e[t++]=r&255|t7,r/=128;for(;r&IB;)e[t++]=r&255|t7,r>>>=7;return e[t]=r|0,r7.bytes=t-n+1,e}});var a7=B((Nte,o7)=>{o7.exports=om;var TB=128,s7=127;function om(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw om.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&s7)<=TB);return om.bytes=s-n,t}});var u7=B((Ote,c7)=>{var DB=Math.pow(2,7),CB=Math.pow(2,14),PB=Math.pow(2,21),kB=Math.pow(2,28),NB=Math.pow(2,35),OB=Math.pow(2,42),BB=Math.pow(2,49),LB=Math.pow(2,56),MB=Math.pow(2,63);c7.exports=function(r){return r{l7.exports={encode:i7(),decode:a7(),encodingLength:u7()}});var p7=B((Lte,d7)=>{"use strict";var h7=f7();d7.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=h7.decode(r);e.push(t),r=r.slice(h7.decode.bytes)}return e}});var y7=B((Wte,g7)=>{g7.exports=am;var m7=128,UB=127,FB=~UB,KB=Math.pow(2,31);function am(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw am.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=KB;)e[t++]=r&255|m7,r/=128;for(;r&FB;)e[t++]=r&255|m7,r>>>=7;return e[t]=r|0,am.bytes=t-n+1,e}});var E7=B((Yte,w7)=>{w7.exports=cm;var VB=128,b7=127;function cm(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a||i>49)throw cm.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&b7)<=VB);return cm.bytes=s-n,t}});var v7=B((Qte,x7)=>{var qB=Math.pow(2,7),zB=Math.pow(2,14),$B=Math.pow(2,21),HB=Math.pow(2,28),GB=Math.pow(2,35),WB=Math.pow(2,42),YB=Math.pow(2,49),QB=Math.pow(2,56),XB=Math.pow(2,63);x7.exports=function(r){return r{_7.exports={encode:y7(),decode:E7(),encodingLength:v7()}});var A7=B((Zte,I7)=>{"use strict";I7.exports=ZB;function ZB(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";var Wh=C7;Wh.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var dc=new Array(64),D7=new Array(123);for(ci=0;ci<64;)D7[dc[ci]=ci<26?ci+65:ci<52?ci+71:ci<62?ci-4:ci-59|43]=ci++;var ci;Wh.encode=function(e,t,n){for(var i=null,s=[],o=0,a=0,c;t>2],c=(u&3)<<4,a=1;break;case 1:s[o++]=dc[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[o++]=dc[c|u>>6],s[o++]=dc[u&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=dc[c],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var T7="invalid encoding";Wh.decode=function(e,t,n){for(var i=n,s=0,o,a=0;a1)break;if((c=D7[c])===void 0)throw Error(T7);switch(s){case 0:o=c,s=1;break;case 1:t[n++]=o<<2|(c&48)>>4,o=c,s=2;break;case 2:t[n++]=(o&15)<<4|(c&60)>>2,o=c,s=3;break;case 3:t[n++]=(o&3)<<6|c,s=0;break}}if(s===1)throw Error(T7);return n-i};Wh.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var N7=B((ere,k7)=>{"use strict";k7.exports=Yh;function Yh(){this._listeners={}}Yh.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Yh.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";F7.exports=O7(O7);function O7(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3]}function s(c,u,l){e[0]=c,u[l]=t[3],u[l+1]=t[2],u[l+2]=t[1],u[l+3]=t[0]}r.writeFloatLE=n?i:s,r.writeFloatBE=n?s:i;function o(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],e[0]}function a(c,u){return t[3]=c[u],t[2]=c[u+1],t[1]=c[u+2],t[0]=c[u+3],e[0]}r.readFloatLE=n?o:a,r.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var c=Math.floor(Math.log(i)/Math.LN2),u=Math.round(i*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,s,o)}}r.writeFloatLE=e.bind(null,B7),r.writeFloatBE=e.bind(null,L7);function t(n,i,s){var o=n(i,s),a=(o>>31)*2+1,c=o>>>23&255,u=o&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}r.readFloatLE=t.bind(null,M7),r.readFloatBE=t.bind(null,U7)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function i(c,u,l){e[0]=c,u[l]=t[0],u[l+1]=t[1],u[l+2]=t[2],u[l+3]=t[3],u[l+4]=t[4],u[l+5]=t[5],u[l+6]=t[6],u[l+7]=t[7]}function s(c,u,l){e[0]=c,u[l]=t[7],u[l+1]=t[6],u[l+2]=t[5],u[l+3]=t[4],u[l+4]=t[3],u[l+5]=t[2],u[l+6]=t[1],u[l+7]=t[0]}r.writeDoubleLE=n?i:s,r.writeDoubleBE=n?s:i;function o(c,u){return t[0]=c[u],t[1]=c[u+1],t[2]=c[u+2],t[3]=c[u+3],t[4]=c[u+4],t[5]=c[u+5],t[6]=c[u+6],t[7]=c[u+7],e[0]}function a(c,u){return t[7]=c[u],t[6]=c[u+1],t[5]=c[u+2],t[4]=c[u+3],t[3]=c[u+4],t[2]=c[u+5],t[1]=c[u+6],t[0]=c[u+7],e[0]}r.readDoubleLE=n?o:a,r.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,c){var u=o<0?1:0;if(u&&(o=-o),o===0)n(0,a,c+i),n(1/o>0?0:2147483648,a,c+s);else if(isNaN(o))n(0,a,c+i),n(2146959360,a,c+s);else if(o>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(o<22250738585072014e-324)l=o/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+s);else{var f=Math.floor(Math.log(o)/Math.LN2);f===1024&&(f=1023),l=o*Math.pow(2,-f),n(l*4503599627370496>>>0,a,c+i),n((u<<31|f+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}r.writeDoubleLE=e.bind(null,B7,0,4),r.writeDoubleBE=e.bind(null,L7,4,0);function t(n,i,s,o,a){var c=n(o,a+i),u=n(o,a+s),l=(u>>31)*2+1,f=u>>>20&2047,h=4294967296*(u&1048575)+c;return f===2047?h?NaN:l*(1/0):f===0?l*5e-324*h:l*Math.pow(2,f-1075)*(h+4503599627370496)}r.readDoubleLE=t.bind(null,M7,0,4),r.readDoubleBE=t.bind(null,U7,4,0)}(),r}function B7(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function L7(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function M7(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function U7(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var V7=B((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var z7=B(q7=>{"use strict";var um=q7;um.length=function(e){for(var t=0,n=0,i=0;i191&&c<224?o[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[a++]=55296+(c>>10),o[a++]=56320+(c&1023)):o[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};um.write=function(e,t,n){for(var i=n,s,o,a=0;a>6|192,t[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,t[n++]=s>>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=s&63|128):(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=s&63|128);return n-i}});var H7=B((nre,$7)=>{"use strict";$7.exports=JB;function JB(r,e,t){var n=t||8192,i=n>>>1,s=null,o=n;return function(c){if(c<1||c>i)return r(c);o+c>n&&(s=r(n),o=0);var u=e.call(s,o,o+=c);return o&7&&(o=(o|7)+1),u}}});var W7=B((ire,G7)=>{"use strict";G7.exports=ir;var xl=ys();function ir(r,e){this.lo=r>>>0,this.hi=e>>>0}var aa=ir.zero=new ir(0,0);aa.toNumber=function(){return 0};aa.zzEncode=aa.zzDecode=function(){return this};aa.length=function(){return 1};var eL=ir.zeroHash="\0\0\0\0\0\0\0\0";ir.fromNumber=function(e){if(e===0)return aa;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new ir(n,i)};ir.from=function(e){if(typeof e=="number")return ir.fromNumber(e);if(xl.isString(e))if(xl.Long)e=xl.Long.fromString(e);else return ir.fromNumber(parseInt(e,10));return e.low||e.high?new ir(e.low>>>0,e.high>>>0):aa};ir.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};ir.prototype.toLong=function(e){return xl.Long?new xl.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Xs=String.prototype.charCodeAt;ir.fromHash=function(e){return e===eL?aa:new ir((Xs.call(e,0)|Xs.call(e,1)<<8|Xs.call(e,2)<<16|Xs.call(e,3)<<24)>>>0,(Xs.call(e,4)|Xs.call(e,5)<<8|Xs.call(e,6)<<16|Xs.call(e,7)<<24)>>>0)};ir.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};ir.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};ir.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};ir.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var ys=B(lm=>{"use strict";var he=lm;he.asPromise=A7();he.base64=P7();he.EventEmitter=N7();he.float=K7();he.inquire=V7();he.utf8=z7();he.pool=H7();he.LongBits=W7();he.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);he.global=he.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||lm;he.emptyArray=Object.freeze?Object.freeze([]):[];he.emptyObject=Object.freeze?Object.freeze({}):{};he.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};he.isString=function(e){return typeof e=="string"||e instanceof String};he.isObject=function(e){return e&&typeof e=="object"};he.isset=he.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};he.Buffer=function(){try{var r=he.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();he._Buffer_from=null;he._Buffer_allocUnsafe=null;he.newBuffer=function(e){return typeof e=="number"?he.Buffer?he._Buffer_allocUnsafe(e):new he.Array(e):he.Buffer?he._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};he.Array=typeof Uint8Array<"u"?Uint8Array:Array;he.Long=he.global.dcodeIO&&he.global.dcodeIO.Long||he.global.Long||he.inquire("long");he.key2Re=/^true|false|0|1$/;he.key32Re=/^-?(?:0|[1-9][0-9]*)$/;he.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;he.longToHash=function(e){return e?he.LongBits.from(e).toHash():he.LongBits.zeroHash};he.longFromHash=function(e,t){var n=he.LongBits.fromHash(e);return he.Long?he.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Y7(r,e,t){for(var n=Object.keys(e),i=0;i-1;--s)if(t[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};he.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";e9.exports=Ft;var Vi=ys(),hm,Z7=Vi.LongBits,tL=Vi.utf8;function ui(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function Ft(r){this.buf=r,this.pos=0,this.len=r.length}var X7=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Ft(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Ft(e);throw Error("illegal buffer")},J7=function(){return Vi.Buffer?function(t){return(Ft.create=function(i){return Vi.Buffer.isBuffer(i)?new hm(i):X7(i)})(t)}:X7};Ft.create=J7();Ft.prototype._slice=Vi.Array.prototype.subarray||Vi.Array.prototype.slice;Ft.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ui(this,10);return e}}();Ft.prototype.int32=function(){return this.uint32()|0};Ft.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function fm(){var r=new Z7(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ui(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw ui(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}Ft.prototype.bool=function(){return this.uint32()!==0};function Qh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}Ft.prototype.fixed32=function(){if(this.pos+4>this.len)throw ui(this,4);return Qh(this.buf,this.pos+=4)};Ft.prototype.sfixed32=function(){if(this.pos+4>this.len)throw ui(this,4);return Qh(this.buf,this.pos+=4)|0};function j7(){if(this.pos+8>this.len)throw ui(this,8);return new Z7(Qh(this.buf,this.pos+=4),Qh(this.buf,this.pos+=4))}Ft.prototype.float=function(){if(this.pos+4>this.len)throw ui(this,4);var e=Vi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Ft.prototype.double=function(){if(this.pos+8>this.len)throw ui(this,4);var e=Vi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Ft.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ui(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)};Ft.prototype.string=function(){var e=this.bytes();return tL.read(e,0,e.length)};Ft.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ui(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ui(this);while(this.buf[this.pos++]&128);return this};Ft.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};Ft._configure=function(r){hm=r,Ft.create=J7(),hm._configure();var e=Vi.Long?"toLong":"toNumber";Vi.merge(Ft.prototype,{int64:function(){return fm.call(this)[e](!1)},uint64:function(){return fm.call(this)[e](!0)},sint64:function(){return fm.call(this).zzDecode()[e](!1)},fixed64:function(){return j7.call(this)[e](!0)},sfixed64:function(){return j7.call(this)[e](!1)}})}});var dm=B((are,n9)=>{"use strict";n9.exports=ca;var r9=Xh();(ca.prototype=Object.create(r9.prototype)).constructor=ca;var t9=ys();function ca(r){r9.call(this,r)}ca._configure=function(){t9.Buffer&&(ca.prototype._slice=t9.Buffer.prototype.slice)};ca.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))};ca._configure()});var Zh=B((cre,a9)=>{"use strict";a9.exports=Ge;var Mn=ys(),pm,jh=Mn.LongBits,i9=Mn.base64,s9=Mn.utf8;function vl(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function gm(){}function rL(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Ge(){this.len=0,this.head=new vl(gm,0,0),this.tail=this.head,this.states=null}var o9=function(){return Mn.Buffer?function(){return(Ge.create=function(){return new pm})()}:function(){return new Ge}};Ge.create=o9();Ge.alloc=function(e){return new Mn.Array(e)};Mn.Array!==Array&&(Ge.alloc=Mn.pool(Ge.alloc,Mn.Array.prototype.subarray));Ge.prototype._push=function(e,t,n){return this.tail=this.tail.next=new vl(e,t,n),this.len+=t,this};function ym(r,e,t){e[t]=r&255}function nL(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function bm(r,e){this.len=r,this.next=void 0,this.val=e}bm.prototype=Object.create(vl.prototype);bm.prototype.fn=nL;Ge.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new bm((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ge.prototype.int32=function(e){return e<0?this._push(wm,10,jh.fromNumber(e)):this.uint32(e)};Ge.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function wm(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}Ge.prototype.uint64=function(e){var t=jh.from(e);return this._push(wm,t.length(),t)};Ge.prototype.int64=Ge.prototype.uint64;Ge.prototype.sint64=function(e){var t=jh.from(e).zzEncode();return this._push(wm,t.length(),t)};Ge.prototype.bool=function(e){return this._push(ym,1,e?1:0)};function mm(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Ge.prototype.fixed32=function(e){return this._push(mm,4,e>>>0)};Ge.prototype.sfixed32=Ge.prototype.fixed32;Ge.prototype.fixed64=function(e){var t=jh.from(e);return this._push(mm,4,t.lo)._push(mm,4,t.hi)};Ge.prototype.sfixed64=Ge.prototype.fixed64;Ge.prototype.float=function(e){return this._push(Mn.float.writeFloatLE,4,e)};Ge.prototype.double=function(e){return this._push(Mn.float.writeDoubleLE,8,e)};var iL=Mn.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(ym,1,0);if(Mn.isString(e)){var n=Ge.alloc(t=i9.length(e));i9.decode(e,n,0),e=n}return this.uint32(t)._push(iL,t,e)};Ge.prototype.string=function(e){var t=s9.length(e);return t?this.uint32(t)._push(s9.write,t,e):this._push(ym,1,0)};Ge.prototype.fork=function(){return this.states=new rL(this),this.head=this.tail=new vl(gm,0,0),this.len=0,this};Ge.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 vl(gm,0,0),this.len=0),this};Ge.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};Ge.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};Ge._configure=function(r){pm=r,Ge.create=o9(),pm._configure()}});var Em=B((ure,u9)=>{"use strict";u9.exports=qi;var c9=Zh();(qi.prototype=Object.create(c9.prototype)).constructor=qi;var js=ys();function qi(){c9.call(this)}qi._configure=function(){qi.alloc=js._Buffer_allocUnsafe,qi.writeBytesBuffer=js.Buffer&&js.Buffer.prototype instanceof Uint8Array&&js.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(qi.writeBytesBuffer,t,e),this};function sL(r,e,t){r.length<40?js.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}qi.prototype.string=function(e){var t=js.Buffer.byteLength(e);return this.uint32(t),t&&this._push(sL,t,e),this};qi._configure()});var x9=B((_ne,E9)=>{"use strict";E9.exports=function(){return Date.now()}});var _9=B((Sne,v9)=>{"use strict";var a0=x9(),Pm=class{constructor(e,t,n){let i=this;this._started=a0(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(a0()-i._started),i._schedule(i._scheduled)):(i._triggered=!0,e.apply(null,i._args))},this._timer=setTimeout(this._timerWrapper,t)}reschedule(e){e||(e=this._scheduled);let t=a0();t+e-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(e)):this._triggered?this._schedule(e):(this._started=t,this._rescheduled=e)}_schedule(e){this._triggered=!1,this._started=a0(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function vL(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var e=0;e{"use strict";var{AbortController:_L}=globalThis,S9=_9(),km=class r extends _L{constructor(e){super(),this._ms=e,this._timer=S9(()=>this.abort(),e),Object.setPrototypeOf(this,r.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=S9(()=>this.abort(),this._ms)}};R9.exports={TimeoutController:km}});var Xr=B((Bne,Mm)=>{"use strict";var gc=typeof Reflect=="object"?Reflect:null,P9=gc&&typeof gc.apply=="function"?gc.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},u0;gc&&typeof gc.ownKeys=="function"?u0=gc.ownKeys:Object.getOwnPropertySymbols?u0=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:u0=function(e){return Object.getOwnPropertyNames(e)};function TL(r){console&&console.warn&&console.warn(r)}var N9=Number.isNaN||function(e){return e!==e};function st(){st.init.call(this)}Mm.exports=st;Mm.exports.once=kL;st.EventEmitter=st;st.prototype._events=void 0;st.prototype._eventsCount=0;st.prototype._maxListeners=void 0;var k9=10;function l0(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(st,"defaultMaxListeners",{enumerable:!0,get:function(){return k9},set:function(r){if(typeof r!="number"||r<0||N9(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");k9=r}});st.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};st.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||N9(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function O9(r){return r._maxListeners===void 0?st.defaultMaxListeners:r._maxListeners}st.prototype.getMaxListeners=function(){return O9(this)};st.prototype.emit=function(e){for(var t=[],n=1;n0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")P9(c,this,t);else for(var u=c.length,l=F9(c,u),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=o.length,TL(a)}return r}st.prototype.addListener=function(e,t){return B9(this,e,t,!1)};st.prototype.on=st.prototype.addListener;st.prototype.prependListener=function(e,t){return B9(this,e,t,!0)};function DL(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function L9(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=DL.bind(n);return i.listener=t,n.wrapFn=i,i}st.prototype.once=function(e,t){return l0(t),this.on(e,L9(this,e,t)),this};st.prototype.prependOnceListener=function(e,t){return l0(t),this.prependListener(e,L9(this,e,t)),this};st.prototype.removeListener=function(e,t){var n,i,s,o,a;if(l0(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():CL(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};st.prototype.off=st.prototype.removeListener;st.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,t[i]);return this};function M9(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?PL(i):F9(i,i.length)}st.prototype.listeners=function(e){return M9(this,e,!0)};st.prototype.rawListeners=function(e){return M9(this,e,!1)};st.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):U9.call(r,e)};st.prototype.listenerCount=U9;function U9(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}st.prototype.eventNames=function(){return this._eventsCount>0?u0(this._events):[]};function F9(r,e){for(var t=new Array(e),n=0;n{"use strict";var OL=Math.exp;$9=H9.exports=function(e){if(typeof e!="number")throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let t,n=0,i=0,s=0,o,a={};function c(u,l){return 1-OL(-(u-l)/e)}return a.push=function(l,f){if(o){let h=c(l,o),d=f-t,p=h*d;t=h*f+(1-h)*t,n=(1-h)*(n+d*p),i=Math.sqrt(n),s=t+h*d}else t=f;o=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return s},a}});var iw=B((hse,Gm)=>{"use strict";var hM=Object.prototype.hasOwnProperty,Ur="~";function kl(){}Object.create&&(kl.prototype=Object.create(null),new kl().__proto__||(Ur=!1));function dM(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function nw(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new dM(t,n||r,i),o=Ur?Ur+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],s]:r._events[o].push(s):(r._events[o]=s,r._eventsCount++),r}function D0(r,e){--r._eventsCount===0?r._events=new kl:delete r._events[e]}function Pr(){this._events=new kl,this._eventsCount=0}Pr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)hM.call(t,n)&&e.push(Ur?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Pr.prototype.listeners=function(e){var t=Ur?Ur+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i{Lw.exports={options:{usePureJavaScript:!1}}});var Fw=B((zoe,Uw)=>{var m3={};Uw.exports=m3;var Mw={};m3.encode=function(r,e,t){if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');if(t!==void 0&&typeof t!="number")throw new TypeError('"maxline" must be a number.');var n="";if(!(r instanceof Uint8Array))n=vM(r,e);else{var i=0,s=e.length,o=e.charAt(0),a=[0];for(i=0;i0;)a.push(u%s),u=u/s|0}for(i=0;r[i]===0&&i=0;--i)n+=e[a[i]]}if(t){var l=new RegExp(".{1,"+t+"}","g");n=n.match(l).join(`\r `)}return n};m3.decode=function(r,e){if(typeof r!="string")throw new TypeError('"input" must be a string.');if(typeof e!="string")throw new TypeError('"alphabet" must be a string.');var t=Mw[e];if(!t){t=Mw[e]=[];for(var n=0;n>=8;for(;u>0;)o.push(u&255),u>>=8}for(var l=0;r[l]===s&&l0;)s.push(a%n),a=a/n|0}var c="";for(t=0;r.at(t)===0&&t=0;--t)c+=e[s[t]];return c}});var Nt=B(($oe,zw)=>{var Kw=Ve(),Vw=Fw(),S=zw.exports=Kw.util=Kw.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){S.nextTick=process.nextTick,typeof setImmediate=="function"?S.setImmediate=setImmediate:S.setImmediate=S.nextTick;return}if(typeof setImmediate=="function"){S.setImmediate=function(){return setImmediate.apply(void 0,arguments)},S.nextTick=function(a){return setImmediate(a)};return}if(S.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage=="function"){let a=function(c){if(c.source===window&&c.data===r){c.stopPropagation();var u=e.slice();e.length=0,u.forEach(function(l){l()})}};var o=a,r="forge.setImmediate",e=[];S.setImmediate=function(c){e.push(c),e.length===1&&window.postMessage(r,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var t=Date.now(),n=!0,i=document.createElement("div"),e=[];new MutationObserver(function(){var c=e.slice();e.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var s=S.setImmediate;S.setImmediate=function(c){Date.now()-t>15?(t=Date.now(),s(c)):(e.push(c),e.length===1&&i.setAttribute("a",n=!n))}}S.nextTick=S.setImmediate})();S.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;S.globalScope=function(){return S.isNodejs?globalThis:typeof self>"u"?window:self}();S.isArray=Array.isArray||function(r){return Object.prototype.toString.call(r)==="[object Array]"};S.isArrayBuffer=function(r){return typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer};S.isArrayBufferView=function(r){return r&&S.isArrayBuffer(r.buffer)&&r.byteLength!==void 0};function Vl(r){if(!(r===8||r===16||r===24||r===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+r)}S.ByteBuffer=g3;function g3(r){if(this.data="",this.read=0,typeof r=="string")this.data=r;else if(S.isArrayBuffer(r)||S.isArrayBufferView(r))if(typeof Buffer<"u"&&r instanceof Buffer)this.data=r.toString("binary");else{var e=new Uint8Array(r);try{this.data=String.fromCharCode.apply(null,e)}catch{for(var t=0;t_M&&(this.data.substr(0,1),this._constructedStringLength=0)};S.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};S.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};S.ByteStringBuffer.prototype.putByte=function(r){return this.putBytes(String.fromCharCode(r))};S.ByteStringBuffer.prototype.fillWithByte=function(r,e){r=String.fromCharCode(r);for(var t=this.data;e>0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return this.data=t,this._optimizeConstructedString(e),this};S.ByteStringBuffer.prototype.putBytes=function(r){return this.data+=r,this._optimizeConstructedString(r.length),this};S.ByteStringBuffer.prototype.putString=function(r){return this.putBytes(S.encodeUtf8(r))};S.ByteStringBuffer.prototype.putInt16=function(r){return this.putBytes(String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};S.ByteStringBuffer.prototype.putInt24=function(r){return this.putBytes(String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};S.ByteStringBuffer.prototype.putInt32=function(r){return this.putBytes(String.fromCharCode(r>>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};S.ByteStringBuffer.prototype.putInt16Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255))};S.ByteStringBuffer.prototype.putInt24Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255))};S.ByteStringBuffer.prototype.putInt32Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>24&255))};S.ByteStringBuffer.prototype.putInt=function(r,e){Vl(e);var t="";do e-=8,t+=String.fromCharCode(r>>e&255);while(e>0);return this.putBytes(t)};S.ByteStringBuffer.prototype.putSignedInt=function(r,e){return r<0&&(r+=2<0);return e};S.ByteStringBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<=t&&(e-=t<<1),e};S.ByteStringBuffer.prototype.getBytes=function(r){var e;return r?(r=Math.min(this.length(),r),e=this.data.slice(this.read,this.read+r),this.read+=r):r===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};S.ByteStringBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};S.ByteStringBuffer.prototype.at=function(r){return this.data.charCodeAt(this.read+r)};S.ByteStringBuffer.prototype.setAt=function(r,e){return this.data=this.data.substr(0,this.read+r)+String.fromCharCode(e)+this.data.substr(this.read+r+1),this};S.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};S.ByteStringBuffer.prototype.copy=function(){var r=S.createBuffer(this.data);return r.read=this.read,r};S.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};S.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};S.ByteStringBuffer.prototype.truncate=function(r){var e=Math.max(0,this.length()-r);return this.data=this.data.substr(this.read,e),this.read=0,this};S.ByteStringBuffer.prototype.toHex=function(){for(var r="",e=this.read;e=r)return this;e=Math.max(e||this.growSize,r);var t=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+e);return n.set(t),this.data=new DataView(n.buffer),this};S.DataBuffer.prototype.putByte=function(r){return this.accommodate(1),this.data.setUint8(this.write++,r),this};S.DataBuffer.prototype.fillWithByte=function(r,e){this.accommodate(e);for(var t=0;t>8&65535),this.data.setInt8(this.write,r>>16&255),this.write+=3,this};S.DataBuffer.prototype.putInt32=function(r){return this.accommodate(4),this.data.setInt32(this.write,r),this.write+=4,this};S.DataBuffer.prototype.putInt16Le=function(r){return this.accommodate(2),this.data.setInt16(this.write,r,!0),this.write+=2,this};S.DataBuffer.prototype.putInt24Le=function(r){return this.accommodate(3),this.data.setInt8(this.write,r>>16&255),this.data.setInt16(this.write,r>>8&65535,!0),this.write+=3,this};S.DataBuffer.prototype.putInt32Le=function(r){return this.accommodate(4),this.data.setInt32(this.write,r,!0),this.write+=4,this};S.DataBuffer.prototype.putInt=function(r,e){Vl(e),this.accommodate(e/8);do e-=8,this.data.setInt8(this.write++,r>>e&255);while(e>0);return this};S.DataBuffer.prototype.putSignedInt=function(r,e){return Vl(e),this.accommodate(e/8),r<0&&(r+=2<0);return e};S.DataBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<=t&&(e-=t<<1),e};S.DataBuffer.prototype.getBytes=function(r){var e;return r?(r=Math.min(this.length(),r),e=this.data.slice(this.read,this.read+r),this.read+=r):r===0?e="":(e=this.read===0?this.data:this.data.slice(this.read),this.clear()),e};S.DataBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};S.DataBuffer.prototype.at=function(r){return this.data.getUint8(this.read+r)};S.DataBuffer.prototype.setAt=function(r,e){return this.data.setUint8(r,e),this};S.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};S.DataBuffer.prototype.copy=function(){return new S.DataBuffer(this)};S.DataBuffer.prototype.compact=function(){if(this.read>0){var r=new Uint8Array(this.data.buffer,this.read),e=new Uint8Array(r.byteLength);e.set(r),this.data=new DataView(e),this.write-=this.read,this.read=0}return this};S.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};S.DataBuffer.prototype.truncate=function(r){return this.write=Math.max(0,this.length()-r),this.read=Math.min(this.read,this.write),this};S.DataBuffer.prototype.toHex=function(){for(var r="",e=this.read;e0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return t};S.xorBytes=function(r,e,t){for(var n="",i="",s="",o=0,a=0;t>0;--t,++o)i=r.charCodeAt(o)^e.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+=s,n};S.hexToBytes=function(r){var e="",t=0;for(r.length&!0&&(t=1,e+=String.fromCharCode(parseInt(r[0],16)));t>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255)};var so="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",oo=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],qw="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";S.encode64=function(r,e){for(var t="",n="",i,s,o,a=0;a>2),t+=so.charAt((i&3)<<4|s>>4),isNaN(s)?t+="==":(t+=so.charAt((s&15)<<2|o>>6),t+=isNaN(o)?"=":so.charAt(o&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r `,t=t.substr(e));return n+=t,n};S.decode64=function(r){r=r.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var e="",t,n,i,s,o=0;o>4),i!==64&&(e+=String.fromCharCode((n&15)<<4|i>>2),s!==64&&(e+=String.fromCharCode((i&3)<<6|s)));return e};S.encodeUtf8=function(r){return unescape(encodeURIComponent(r))};S.decodeUtf8=function(r){return decodeURIComponent(escape(r))};S.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Vw.encode,decode:Vw.decode}};S.binary.raw.encode=function(r){return String.fromCharCode.apply(null,r)};S.binary.raw.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,s=0;s>2),t+=so.charAt((i&3)<<4|s>>4),isNaN(s)?t+="==":(t+=so.charAt((s&15)<<2|o>>6),t+=isNaN(o)?"=":so.charAt(o&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r `,t=t.substr(e));return n+=t,n};S.binary.base64.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(Math.ceil(r.length/4)*3)),r=r.replace(/[^A-Za-z0-9\+\/\=]/g,""),t=t||0;for(var i,s,o,a,c=0,u=t;c>4,o!==64&&(n[u++]=(s&15)<<4|o>>2,a!==64&&(n[u++]=(o&3)<<6|a));return e?u-t:n.subarray(0,u)};S.binary.base58.encode=function(r,e){return S.binary.baseN.encode(r,qw,e)};S.binary.base58.decode=function(r,e){return S.binary.baseN.decode(r,qw,e)};S.text={utf8:{},utf16:{}};S.text.utf8.encode=function(r,e,t){r=S.encodeUtf8(r);var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,s=0;s"u"&&(t=["web","flash"]);var i,s=!1,o=null;for(var a in t){i=t[a];try{if(i==="flash"||i==="both"){if(e[0]===null)throw new Error("Flash local storage not available.");n=r.apply(this,e),s=i==="flash"}(i==="web"||i==="both")&&(e[0]=localStorage,n=r.apply(this,e),s=!0)}catch(c){o=c}if(s)break}if(!s)throw o;return n};S.setItem=function(r,e,t,n,i){z0(RM,arguments,i)};S.getItem=function(r,e,t,n){return z0(IM,arguments,n)};S.removeItem=function(r,e,t,n){z0(AM,arguments,n)};S.clearItems=function(r,e,t){z0(TM,arguments,t)};S.isEmpty=function(r){for(var e in r)if(r.hasOwnProperty(e))return!1;return!0};S.format=function(r){for(var e=/%./g,t,n,i=0,s=[],o=0;t=e.exec(r);){n=r.substring(o,e.lastIndex-2),n.length>0&&s.push(n),o=e.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(r.substring(o)),s.join("")};S.formatNumber=function(r,e,t,n){var i=r,s=isNaN(e=Math.abs(e))?2:e,o=t===void 0?",":t,a=n===void 0?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(s?o+Math.abs(i-u).toFixed(s).slice(2):"")};S.formatSize=function(r){return r>=1073741824?r=S.formatNumber(r/1073741824,2,".","")+" GiB":r>=1048576?r=S.formatNumber(r/1048576,2,".","")+" MiB":r>=1024?r=S.formatNumber(r/1024,0)+" KiB":r=S.formatNumber(r,0)+" bytes",r};S.bytesFromIP=function(r){return r.indexOf(".")!==-1?S.bytesFromIPv4(r):r.indexOf(":")!==-1?S.bytesFromIPv6(r):null};S.bytesFromIPv4=function(r){if(r=r.split("."),r.length!==4)return null;for(var e=S.createBuffer(),t=0;tt[n].end-t[n].start&&(n=t.length-1))}e.push(s)}if(t.length>0){var c=t[n];c.end-c.start>0&&(e.splice(c.start,c.end-c.start+1,""),c.start===0&&e.unshift(""),c.end===7&&e.push(""))}return e.join(":")};S.estimateCores=function(r,e){if(typeof r=="function"&&(e=r,r={}),r=r||{},"cores"in S&&!r.update)return e(null,S.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return S.cores=navigator.hardwareConcurrency,e(null,S.cores);if(typeof Worker>"u")return S.cores=1,e(null,S.cores);if(typeof Blob>"u")return S.cores=2,e(null,S.cores);var t=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(o){for(var a=Date.now(),c=a+4;Date.now()d.st&&l.stl.st&&d.st{var ql=Ve();ql.pki=ql.pki||{};var w3=$w.exports=ql.pki.oids=ql.oids=ql.oids||{};function z(r,e){w3[r]=e,w3[e]=r}function rt(r,e){w3[r]=e}z("1.2.840.113549.1.1.1","rsaEncryption");z("1.2.840.113549.1.1.4","md5WithRSAEncryption");z("1.2.840.113549.1.1.5","sha1WithRSAEncryption");z("1.2.840.113549.1.1.7","RSAES-OAEP");z("1.2.840.113549.1.1.8","mgf1");z("1.2.840.113549.1.1.9","pSpecified");z("1.2.840.113549.1.1.10","RSASSA-PSS");z("1.2.840.113549.1.1.11","sha256WithRSAEncryption");z("1.2.840.113549.1.1.12","sha384WithRSAEncryption");z("1.2.840.113549.1.1.13","sha512WithRSAEncryption");z("1.3.101.112","EdDSA25519");z("1.2.840.10040.4.3","dsa-with-sha1");z("1.3.14.3.2.7","desCBC");z("1.3.14.3.2.26","sha1");z("1.3.14.3.2.29","sha1WithRSASignature");z("2.16.840.1.101.3.4.2.1","sha256");z("2.16.840.1.101.3.4.2.2","sha384");z("2.16.840.1.101.3.4.2.3","sha512");z("2.16.840.1.101.3.4.2.4","sha224");z("2.16.840.1.101.3.4.2.5","sha512-224");z("2.16.840.1.101.3.4.2.6","sha512-256");z("1.2.840.113549.2.2","md2");z("1.2.840.113549.2.5","md5");z("1.2.840.113549.1.7.1","data");z("1.2.840.113549.1.7.2","signedData");z("1.2.840.113549.1.7.3","envelopedData");z("1.2.840.113549.1.7.4","signedAndEnvelopedData");z("1.2.840.113549.1.7.5","digestedData");z("1.2.840.113549.1.7.6","encryptedData");z("1.2.840.113549.1.9.1","emailAddress");z("1.2.840.113549.1.9.2","unstructuredName");z("1.2.840.113549.1.9.3","contentType");z("1.2.840.113549.1.9.4","messageDigest");z("1.2.840.113549.1.9.5","signingTime");z("1.2.840.113549.1.9.6","counterSignature");z("1.2.840.113549.1.9.7","challengePassword");z("1.2.840.113549.1.9.8","unstructuredAddress");z("1.2.840.113549.1.9.14","extensionRequest");z("1.2.840.113549.1.9.20","friendlyName");z("1.2.840.113549.1.9.21","localKeyId");z("1.2.840.113549.1.9.22.1","x509Certificate");z("1.2.840.113549.1.12.10.1.1","keyBag");z("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");z("1.2.840.113549.1.12.10.1.3","certBag");z("1.2.840.113549.1.12.10.1.4","crlBag");z("1.2.840.113549.1.12.10.1.5","secretBag");z("1.2.840.113549.1.12.10.1.6","safeContentsBag");z("1.2.840.113549.1.5.13","pkcs5PBES2");z("1.2.840.113549.1.5.12","pkcs5PBKDF2");z("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");z("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");z("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");z("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");z("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");z("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");z("1.2.840.113549.2.7","hmacWithSHA1");z("1.2.840.113549.2.8","hmacWithSHA224");z("1.2.840.113549.2.9","hmacWithSHA256");z("1.2.840.113549.2.10","hmacWithSHA384");z("1.2.840.113549.2.11","hmacWithSHA512");z("1.2.840.113549.3.7","des-EDE3-CBC");z("2.16.840.1.101.3.4.1.2","aes128-CBC");z("2.16.840.1.101.3.4.1.22","aes192-CBC");z("2.16.840.1.101.3.4.1.42","aes256-CBC");z("2.5.4.3","commonName");z("2.5.4.4","surname");z("2.5.4.5","serialNumber");z("2.5.4.6","countryName");z("2.5.4.7","localityName");z("2.5.4.8","stateOrProvinceName");z("2.5.4.9","streetAddress");z("2.5.4.10","organizationName");z("2.5.4.11","organizationalUnitName");z("2.5.4.12","title");z("2.5.4.13","description");z("2.5.4.15","businessCategory");z("2.5.4.17","postalCode");z("2.5.4.42","givenName");z("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");z("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");z("2.16.840.1.113730.1.1","nsCertType");z("2.16.840.1.113730.1.13","nsComment");rt("2.5.29.1","authorityKeyIdentifier");rt("2.5.29.2","keyAttributes");rt("2.5.29.3","certificatePolicies");rt("2.5.29.4","keyUsageRestriction");rt("2.5.29.5","policyMapping");rt("2.5.29.6","subtreesConstraint");rt("2.5.29.7","subjectAltName");rt("2.5.29.8","issuerAltName");rt("2.5.29.9","subjectDirectoryAttributes");rt("2.5.29.10","basicConstraints");rt("2.5.29.11","nameConstraints");rt("2.5.29.12","policyConstraints");rt("2.5.29.13","basicConstraints");z("2.5.29.14","subjectKeyIdentifier");z("2.5.29.15","keyUsage");rt("2.5.29.16","privateKeyUsagePeriod");z("2.5.29.17","subjectAltName");z("2.5.29.18","issuerAltName");z("2.5.29.19","basicConstraints");rt("2.5.29.20","cRLNumber");rt("2.5.29.21","cRLReason");rt("2.5.29.22","expirationDate");rt("2.5.29.23","instructionCode");rt("2.5.29.24","invalidityDate");rt("2.5.29.25","cRLDistributionPoints");rt("2.5.29.26","issuingDistributionPoint");rt("2.5.29.27","deltaCRLIndicator");rt("2.5.29.28","issuingDistributionPoint");rt("2.5.29.29","certificateIssuer");rt("2.5.29.30","nameConstraints");z("2.5.29.31","cRLDistributionPoints");z("2.5.29.32","certificatePolicies");rt("2.5.29.33","policyMappings");rt("2.5.29.34","policyConstraints");z("2.5.29.35","authorityKeyIdentifier");rt("2.5.29.36","policyConstraints");z("2.5.29.37","extKeyUsage");rt("2.5.29.46","freshestCRL");rt("2.5.29.54","inhibitAnyPolicy");z("1.3.6.1.4.1.11129.2.4.2","timestampList");z("1.3.6.1.5.5.7.1.1","authorityInfoAccess");z("1.3.6.1.5.5.7.3.1","serverAuth");z("1.3.6.1.5.5.7.3.2","clientAuth");z("1.3.6.1.5.5.7.3.3","codeSigning");z("1.3.6.1.5.5.7.3.4","emailProtection");z("1.3.6.1.5.5.7.3.8","timeStamping")});var ma=B((Goe,Gw)=>{var mt=Ve();Nt();$0();var ee=Gw.exports=mt.asn1=mt.asn1||{};ee.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};ee.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};ee.create=function(r,e,t,n,i){if(mt.util.isArray(n)){for(var s=[],o=0;oe){var n=new Error("Too few bytes to parse DER.");throw n.available=r.length(),n.remaining=e,n.requested=t,n}}var DM=function(r,e){var t=r.getByte();if(e--,t!==128){var n,i=t&128;if(!i)n=t;else{var s=t&127;zl(r,e,s),n=r.getInt(s<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};ee.fromDer=function(r,e){e===void 0&&(e={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof e=="boolean"&&(e={strict:e,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in e||(e.strict=!0),"parseAllBytes"in e||(e.parseAllBytes=!0),"decodeBitStrings"in e||(e.decodeBitStrings=!0),typeof r=="string"&&(r=mt.util.createBuffer(r));var t=r.length(),n=H0(r,r.length(),0,e);if(e.parseAllBytes&&r.length()!==0){var i=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=t,i.remaining=r.length(),i}return n};function H0(r,e,t,n){var i;zl(r,e,2);var s=r.getByte();e--;var o=s&192,a=s&31;i=r.length();var c=DM(r,e);if(e-=i-r.length(),c!==void 0&&c>e){if(n.strict){var u=new Error("Too few bytes to read ASN.1 value.");throw u.available=r.length(),u.remaining=e,u.requested=c,u}c=e}var l,f,h=(s&32)===32;if(h)if(l=[],c===void 0)for(;;){if(zl(r,e,2),r.bytes(2)===String.fromCharCode(0,0)){r.getBytes(2),e-=2;break}i=r.length(),l.push(H0(r,e,t+1,n)),e-=i-r.length()}else for(;c>0;)i=r.length(),l.push(H0(r,c,t+1,n)),e-=i-r.length(),c-=i-r.length();if(l===void 0&&o===ee.Class.UNIVERSAL&&a===ee.Type.BITSTRING&&(f=r.bytes(c)),l===void 0&&n.decodeBitStrings&&o===ee.Class.UNIVERSAL&&a===ee.Type.BITSTRING&&c>1){var d=r.read,p=e,m=0;if(a===ee.Type.BITSTRING&&(zl(r,e,1),m=r.getByte(),e--),m===0)try{i=r.length();var g={strict:!0,decodeBitStrings:!0},y=H0(r,e,t+1,g),b=i-r.length();e-=b,a==ee.Type.BITSTRING&&b++;var E=y.tagClass;b===c&&(E===ee.Class.UNIVERSAL||E===ee.Class.CONTEXT_SPECIFIC)&&(l=[y])}catch{}l===void 0&&(r.read=d,e=p)}if(l===void 0){if(c===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");c=e}if(a===ee.Type.BMPSTRING)for(l="";c>0;c-=2)zl(r,e,2),l+=String.fromCharCode(r.getInt16()),e-=2;else l=r.getBytes(c),e-=c}var _=f===void 0?null:{bitStringContents:f};return ee.create(o,a,h,l,_)}ee.toDer=function(r){var e=mt.util.createBuffer(),t=r.tagClass|r.type,n=mt.util.createBuffer(),i=!1;if("bitStringContents"in r&&(i=!0,r.original&&(i=ee.equals(r,r.original))),i)n.putBytes(r.bitStringContents);else if(r.composed){r.constructed?t|=32:n.putByte(0);for(var s=0;s1&&(r.value.charCodeAt(0)===0&&!(r.value.charCodeAt(1)&128)||r.value.charCodeAt(0)===255&&(r.value.charCodeAt(1)&128)===128)?n.putBytes(r.value.substr(1)):n.putBytes(r.value);if(e.putByte(t),n.length()<=127)e.putByte(n.length()&127);else{var o=n.length(),a="";do a+=String.fromCharCode(o&255),o=o>>>8;while(o>0);e.putByte(a.length|128);for(var s=a.length-1;s>=0;--s)e.putByte(a.charCodeAt(s))}return e.putBuffer(n),e};ee.oidToDer=function(r){var e=r.split("."),t=mt.util.createBuffer();t.putByte(40*parseInt(e[0],10)+parseInt(e[1],10));for(var n,i,s,o,a=2;a>>7,n||(o|=128),i.push(o),n=!1;while(s>0);for(var c=i.length-1;c>=0;--c)t.putByte(i[c])}return t};ee.derToOid=function(r){var e;typeof r=="string"&&(r=mt.util.createBuffer(r));var t=r.getByte();e=Math.floor(t/40)+"."+t%40;for(var n=0;r.length()>0;)t=r.getByte(),n=n<<7,t&128?n+=t&127:(e+="."+(n+t),n=0);return e};ee.utcTimeToDate=function(r){var e=new Date,t=parseInt(r.substr(0,2),10);t=t>=50?1900+t:2e3+t;var n=parseInt(r.substr(2,2),10)-1,i=parseInt(r.substr(4,2),10),s=parseInt(r.substr(6,2),10),o=parseInt(r.substr(8,2),10),a=0;if(r.length>11){var c=r.charAt(10),u=10;c!=="+"&&c!=="-"&&(a=parseInt(r.substr(10,2),10),u+=2)}if(e.setUTCFullYear(t,n,i),e.setUTCHours(s,o,a,0),u&&(c=r.charAt(u),c==="+"||c==="-")){var l=parseInt(r.substr(u+1,2),10),f=parseInt(r.substr(u+4,2),10),h=l*60+f;h*=6e4,c==="+"?e.setTime(+e-h):e.setTime(+e+h)}return e};ee.generalizedTimeToDate=function(r){var e=new Date,t=parseInt(r.substr(0,4),10),n=parseInt(r.substr(4,2),10)-1,i=parseInt(r.substr(6,2),10),s=parseInt(r.substr(8,2),10),o=parseInt(r.substr(10,2),10),a=parseInt(r.substr(12,2),10),c=0,u=0,l=!1;r.charAt(r.length-1)==="Z"&&(l=!0);var f=r.length-5,h=r.charAt(f);if(h==="+"||h==="-"){var d=parseInt(r.substr(f+1,2),10),p=parseInt(r.substr(f+4,2),10);u=d*60+p,u*=6e4,h==="+"&&(u*=-1),l=!0}return r.charAt(14)==="."&&(c=parseFloat(r.substr(14),10)*1e3),l?(e.setUTCFullYear(t,n,i),e.setUTCHours(s,o,a,c),e.setTime(+e+u)):(e.setFullYear(t,n,i),e.setHours(s,o,a,c)),e};ee.dateToUtcTime=function(r){if(typeof r=="string")return r;var e="",t=[];t.push((""+r.getUTCFullYear()).substr(2)),t.push(""+(r.getUTCMonth()+1)),t.push(""+r.getUTCDate()),t.push(""+r.getUTCHours()),t.push(""+r.getUTCMinutes()),t.push(""+r.getUTCSeconds());for(var n=0;n=-128&&r<128)return e.putSignedInt(r,8);if(r>=-32768&&r<32768)return e.putSignedInt(r,16);if(r>=-8388608&&r<8388608)return e.putSignedInt(r,24);if(r>=-2147483648&&r<2147483648)return e.putSignedInt(r,32);var t=new Error("Integer too large; max is 32-bits.");throw t.integer=r,t};ee.derToInteger=function(r){typeof r=="string"&&(r=mt.util.createBuffer(r));var e=r.length()*8;if(e>32)throw new Error("Integer too large; max is 32-bits.");return r.getSignedInt(e)};ee.validate=function(r,e,t,n){var i=!1;if((r.tagClass===e.tagClass||typeof e.tagClass>"u")&&(r.type===e.type||typeof e.type>"u"))if(r.constructed===e.constructed||typeof e.constructed>"u"){if(i=!0,e.value&&mt.util.isArray(e.value))for(var s=0,o=0;i&&o0&&(n+=` `);for(var i="",s=0;s1?n+="0x"+mt.util.bytesToHex(r.value.slice(1)):n+="(none)",r.value.length>0){var u=r.value.charCodeAt(0);u==1?n+=" (1 unused bit shown)":u>1&&(n+=" ("+u+" unused bits shown)")}}else if(r.type===ee.Type.OCTETSTRING)Hw.test(r.value)||(n+="("+r.value+") "),n+="0x"+mt.util.bytesToHex(r.value);else if(r.type===ee.Type.UTF8)try{n+=mt.util.decodeUtf8(r.value)}catch(l){if(l.message==="URI malformed")n+="0x"+mt.util.bytesToHex(r.value)+" (malformed UTF8)";else throw l}else r.type===ee.Type.PRINTABLESTRING||r.type===ee.Type.IA5String?n+=r.value:Hw.test(r.value)?n+="0x"+mt.util.bytesToHex(r.value):r.value.length===0?n+="[null]":n+=r.value}return n}});var x3=B((Woe,Ww)=>{var ar=Ve();Nt();Ww.exports=ar.cipher=ar.cipher||{};ar.cipher.algorithms=ar.cipher.algorithms||{};ar.cipher.createCipher=function(r,e){var t=r;if(typeof t=="string"&&(t=ar.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new ar.cipher.BlockCipher({algorithm:t,key:e,decrypt:!1})};ar.cipher.createDecipher=function(r,e){var t=r;if(typeof t=="string"&&(t=ar.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new ar.cipher.BlockCipher({algorithm:t,key:e,decrypt:!0})};ar.cipher.registerAlgorithm=function(r,e){r=r.toUpperCase(),ar.cipher.algorithms[r]=e};ar.cipher.getAlgorithm=function(r){return r=r.toUpperCase(),r in ar.cipher.algorithms?ar.cipher.algorithms[r]:null};var E3=ar.cipher.BlockCipher=function(r){this.algorithm=r.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=r.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=r.decrypt,this.algorithm.initialize(r)};E3.prototype.start=function(r){r=r||{};var e={};for(var t in r)e[t]=r[t];e.decrypt=this._decrypt,this._finish=!1,this._input=ar.util.createBuffer(),this.output=r.output||ar.util.createBuffer(),this.mode.start(e)};E3.prototype.update=function(r){for(r&&this._input.putBuffer(r);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};E3.prototype.finish=function(r){r&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(t){return r(this.blockSize,t,!1)},this.mode.unpad=function(t){return r(this.blockSize,t,!0)});var e={};return e.decrypt=this._decrypt,e.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,e)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,e))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,e))}});var _3=B((Yoe,Yw)=>{var cr=Ve();Nt();cr.cipher=cr.cipher||{};var Ue=Yw.exports=cr.cipher.modes=cr.cipher.modes||{};Ue.ecb=function(r){r=r||{},this.name="ECB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Ue.ecb.prototype.start=function(r){};Ue.ecb.prototype.encrypt=function(r,e,t){if(r.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};Ue.cbc=function(r){r=r||{},this.name="CBC",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Ue.cbc.prototype.start=function(r){if(r.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in r)this._iv=G0(r.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};Ue.cbc.prototype.encrypt=function(r,e,t){if(r.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};Ue.cfb=function(r){r=r||{},this.name="CFB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=cr.util.createBuffer(),this._partialBytes=0};Ue.cfb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=G0(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Ue.cfb.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Ue.cfb.prototype.decrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Ue.ofb=function(r){r=r||{},this.name="OFB",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=cr.util.createBuffer(),this._partialBytes=0};Ue.ofb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=G0(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Ue.ofb.prototype.encrypt=function(r,e,t){var n=r.length();if(r.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0)r.read-=this.blockSize;else for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Ue.ofb.prototype.decrypt=Ue.ofb.prototype.encrypt;Ue.ctr=function(r){r=r||{},this.name="CTR",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=cr.util.createBuffer(),this._partialBytes=0};Ue.ctr.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=G0(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Ue.ctr.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&(r.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}W0(this._inBlock)};Ue.ctr.prototype.decrypt=Ue.ctr.prototype.encrypt;Ue.gcm=function(r){r=r||{},this.name="GCM",this.cipher=r.cipher,this.blockSize=r.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=cr.util.createBuffer(),this._partialBytes=0,this._R=3774873600};Ue.gcm.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");var e=cr.util.createBuffer(r.iv);this._cipherLength=0;var t;if("additionalData"in r?t=cr.util.createBuffer(r.additionalData):t=cr.util.createBuffer(),"tagLength"in r?this._tagLength=r.tagLength:this._tagLength=128,this._tag=null,r.decrypt&&(this._tag=cr.util.createBuffer(r.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=e.length();if(n===12)this._j0=[e.getInt32(),e.getInt32(),e.getInt32(),1];else{for(this._j0=[0,0,0,0];e.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[e.getInt32(),e.getInt32(),e.getInt32(),e.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(v3(n*8)))}this._inBlock=this._j0.slice(0),W0(this._inBlock),this._partialBytes=0,t=cr.util.createBuffer(t),this._aDataLength=v3(t.length()*8);var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])};Ue.gcm.prototype.encrypt=function(r,e,t){var n=r.length();if(n===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return r.read-=this.blockSize,e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),W0(this._inBlock)};Ue.gcm.prototype.decrypt=function(r,e,t){var n=r.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),W0(this._inBlock),this._hashBlock[0]=r.getInt32(),this._hashBlock[1]=r.getInt32(),this._hashBlock[2]=r.getInt32(),this._hashBlock[3]=r.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)e[n]=r[n]>>>1|(r[n-1]&1)<<31;e[0]=r[0]>>>1,t&&(e[0]^=this._R)};Ue.gcm.prototype.tableMultiply=function(r){for(var e=[0,0,0,0],t=0;t<32;++t){var n=t/8|0,i=r[n]>>>(7-t%8)*4&15,s=this._m[t][i];e[0]^=s[0],e[1]^=s[1],e[2]^=s[2],e[3]^=s[3]}return e};Ue.gcm.prototype.ghash=function(r,e,t){return e[0]^=t[0],e[1]^=t[1],e[2]^=t[2],e[3]^=t[3],this.tableMultiply(e)};Ue.gcm.prototype.generateHashTable=function(r,e){for(var t=8/e,n=4*t,i=16*t,s=new Array(i),o=0;o>>1,i=new Array(t);i[n]=r.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s4){var t=r;r=cr.util.createBuffer();for(var n=0;n{var ht=Ve();x3();_3();Nt();Zw.exports=ht.aes=ht.aes||{};ht.aes.startEncrypting=function(r,e,t,n){var i=Y0({key:r,output:t,decrypt:!1,mode:n});return i.start(e),i};ht.aes.createEncryptionCipher=function(r,e){return Y0({key:r,output:null,decrypt:!1,mode:e})};ht.aes.startDecrypting=function(r,e,t,n){var i=Y0({key:r,output:t,decrypt:!0,mode:n});return i.start(e),i};ht.aes.createDecryptionCipher=function(r,e){return Y0({key:r,output:null,decrypt:!0,mode:e})};ht.aes.Algorithm=function(r,e){I3||Xw();var t=this;t.name=r,t.mode=new e({blockSize:16,cipher:{encrypt:function(n,i){return R3(t._w,n,i,!1)},decrypt:function(n,i){return R3(t._w,n,i,!0)}}}),t._init=!1};ht.aes.Algorithm.prototype.initialize=function(r){if(!this._init){var e=r.key,t;if(typeof e=="string"&&(e.length===16||e.length===24||e.length===32))e=ht.util.createBuffer(e);else if(ht.util.isArray(e)&&(e.length===16||e.length===24||e.length===32)){t=e,e=ht.util.createBuffer();for(var n=0;n>>2;for(var n=0;n>8^a&255^99,Fr[t]=a,S3[a]=t,c=r[a],i=r[t],s=r[i],o=r[s],u=c<<24^a<<16^a<<8^(a^c),l=(i^s^o)<<24^(t^o)<<16^(t^s^o)<<8^(t^i^o);for(var f=0;f<4;++f)ga[f][t]=u,di[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;t===0?t=n=1:(t=i^r[r[r[i^o]]],n^=r[r[n]])}}function jw(r,e){for(var t=r.slice(0),n,i=1,s=t.length,o=s+6+1,a=Rc*o,c=s;c>>16&255]<<24^Fr[n>>>8&255]<<16^Fr[n&255]<<8^Fr[n>>>24]^Qw[i]<<24,i++):s>6&&c%s===4&&(n=Fr[n>>>24]<<24^Fr[n>>>16&255]<<16^Fr[n>>>8&255]<<8^Fr[n&255]),t[c]=t[c-s]^n;if(e){var u,l=di[0],f=di[1],h=di[2],d=di[3],p=t.slice(0);a=t.length;for(var c=0,m=a-Rc;c>>24]]^f[Fr[u>>>16&255]]^h[Fr[u>>>8&255]]^d[Fr[u&255]];t=p}return t}function R3(r,e,t,n){var i=r.length/4-1,s,o,a,c,u;n?(s=di[0],o=di[1],a=di[2],c=di[3],u=S3):(s=ga[0],o=ga[1],a=ga[2],c=ga[3],u=Fr);var l,f,h,d,p,m,g;l=e[0]^r[0],f=e[n?3:1]^r[1],h=e[2]^r[2],d=e[n?1:3]^r[3];for(var y=3,b=1;b>>24]^o[f>>>16&255]^a[h>>>8&255]^c[d&255]^r[++y],m=s[f>>>24]^o[h>>>16&255]^a[d>>>8&255]^c[l&255]^r[++y],g=s[h>>>24]^o[d>>>16&255]^a[l>>>8&255]^c[f&255]^r[++y],d=s[d>>>24]^o[l>>>16&255]^a[f>>>8&255]^c[h&255]^r[++y],l=p,f=m,h=g;t[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[h>>>8&255]<<8^u[d&255]^r[++y],t[n?3:1]=u[f>>>24]<<24^u[h>>>16&255]<<16^u[d>>>8&255]<<8^u[l&255]^r[++y],t[2]=u[h>>>24]<<24^u[d>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^r[++y],t[n?1:3]=u[d>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[h&255]^r[++y]}function Y0(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="AES-"+e,n;r.decrypt?n=ht.cipher.createDecipher(t,r.key):n=ht.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(s,o){var a=null;o instanceof ht.util.ByteBuffer&&(a=o,o={}),o=o||{},o.output=a,o.iv=s,i.call(n,o)},n}});var tE=B((Xoe,eE)=>{var vt=Ve();x3();_3();Nt();eE.exports=vt.des=vt.des||{};vt.des.startEncrypting=function(r,e,t,n){var i=X0({key:r,output:t,decrypt:!1,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};vt.des.createEncryptionCipher=function(r,e){return X0({key:r,output:null,decrypt:!1,mode:e})};vt.des.startDecrypting=function(r,e,t,n){var i=X0({key:r,output:t,decrypt:!0,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};vt.des.createDecryptionCipher=function(r,e){return X0({key:r,output:null,decrypt:!0,mode:e})};vt.des.Algorithm=function(r,e){var t=this;t.name=r,t.mode=new e({blockSize:8,cipher:{encrypt:function(n,i){return Jw(t._keys,n,i,!1)},decrypt:function(n,i){return Jw(t._keys,n,i,!0)}}}),t._init=!1};vt.des.Algorithm.prototype.initialize=function(r){if(!this._init){var e=vt.util.createBuffer(r.key);if(this.name.indexOf("3DES")===0&&e.length()!==24)throw new Error("Invalid Triple-DES key size: "+e.length()*8);this._keys=UM(e),this._init=!0}};$i("DES-ECB",vt.cipher.modes.ecb);$i("DES-CBC",vt.cipher.modes.cbc);$i("DES-CFB",vt.cipher.modes.cfb);$i("DES-OFB",vt.cipher.modes.ofb);$i("DES-CTR",vt.cipher.modes.ctr);$i("3DES-ECB",vt.cipher.modes.ecb);$i("3DES-CBC",vt.cipher.modes.cbc);$i("3DES-CFB",vt.cipher.modes.cfb);$i("3DES-OFB",vt.cipher.modes.ofb);$i("3DES-CTR",vt.cipher.modes.ctr);function $i(r,e){var t=function(){return new vt.des.Algorithm(r,e)};vt.cipher.registerAlgorithm(r,t)}var CM=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],PM=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],kM=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],NM=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],OM=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],BM=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],LM=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],MM=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function UM(r){for(var e=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],t=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],o=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],m=r.length()>8?3:1,g=[],y=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],b=0,E,_=0;_>>4^v)&252645135,v^=E,x^=E<<4,E=(v>>>-16^x)&65535,x^=E,v^=E<<-16,E=(x>>>2^v)&858993459,v^=E,x^=E<<2,E=(v>>>-16^x)&65535,x^=E,v^=E<<-16,E=(x>>>1^v)&1431655765,v^=E,x^=E<<1,E=(v>>>8^x)&16711935,x^=E,v^=E<<8,E=(x>>>1^v)&1431655765,v^=E,x^=E<<1,E=x<<8|v>>>20&240,x=v<<24|v<<8&16711680|v>>>8&65280|v>>>24&240,v=E;for(var R=0;R>>26,v=v<<2|v>>>26):(x=x<<1|x>>>27,v=v<<1|v>>>27),x&=-15,v&=-15;var T=e[x>>>28]|t[x>>>24&15]|n[x>>>20&15]|i[x>>>16&15]|s[x>>>12&15]|o[x>>>8&15]|a[x>>>4&15],P=c[v>>>28]|u[v>>>24&15]|l[v>>>20&15]|f[v>>>16&15]|h[v>>>12&15]|d[v>>>8&15]|p[v>>>4&15];E=(P>>>16^T)&65535,g[b++]=T^E,g[b++]=P^E<<16}}return g}function Jw(r,e,t,n){var i=r.length===32?3:9,s;i===3?s=n?[30,-2,-2]:[0,32,2]:s=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var o,a=e[0],c=e[1];o=(a>>>4^c)&252645135,c^=o,a^=o<<4,o=(a>>>16^c)&65535,c^=o,a^=o<<16,o=(c>>>2^a)&858993459,a^=o,c^=o<<2,o=(c>>>8^a)&16711935,a^=o,c^=o<<8,o=(a>>>1^c)&1431655765,c^=o,a^=o<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u>>4|c<<28)^r[h+1];o=a,a=c,c=o^(PM[d>>>24&63]|NM[d>>>16&63]|BM[d>>>8&63]|MM[d&63]|CM[p>>>24&63]|kM[p>>>16&63]|OM[p>>>8&63]|LM[p&63])}o=a,a=c,c=o}a=a>>>1|a<<31,c=c>>>1|c<<31,o=(a>>>1^c)&1431655765,c^=o,a^=o<<1,o=(c>>>8^a)&16711935,a^=o,c^=o<<8,o=(c>>>2^a)&858993459,a^=o,c^=o<<2,o=(a>>>16^c)&65535,c^=o,a^=o<<16,o=(a>>>4^c)&252645135,c^=o,a^=o<<4,t[0]=a,t[1]=c}function X0(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="DES-"+e,n;r.decrypt?n=vt.cipher.createDecipher(t,r.key):n=vt.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(s,o){var a=null;o instanceof vt.util.ByteBuffer&&(a=o,o={}),o=o||{},o.output=a,o.iv=s,i.call(n,o)},n}});var ya=B((joe,rE)=>{var j0=Ve();rE.exports=j0.md=j0.md||{};j0.md.algorithms=j0.md.algorithms||{}});var iE=B((Zoe,nE)=>{var xs=Ve();ya();Nt();var FM=nE.exports=xs.hmac=xs.hmac||{};FM.create=function(){var r=null,e=null,t=null,n=null,i={};return i.start=function(s,o){if(s!==null)if(typeof s=="string")if(s=s.toLowerCase(),s in xs.md.algorithms)e=xs.md.algorithms[s].create();else throw new Error('Unknown hash algorithm "'+s+'"');else e=s;if(o===null)o=r;else{if(typeof o=="string")o=xs.util.createBuffer(o);else if(xs.util.isArray(o)){var a=o;o=xs.util.createBuffer();for(var c=0;ce.blockLength&&(e.start(),e.update(o.bytes()),o=e.digest()),t=xs.util.createBuffer(),n=xs.util.createBuffer(),u=o.length();for(var c=0;c{});var A3=B((tae,sE)=>{var Kr=Ve();iE();ya();Nt();var KM=Kr.pkcs5=Kr.pkcs5||{},vs;Kr.util.isNodejs&&!Kr.options.usePureJavaScript&&(vs=ba());sE.exports=Kr.pbkdf2=KM.pbkdf2=function(r,e,t,n,i,s){if(typeof i=="function"&&(s=i,i=null),Kr.util.isNodejs&&!Kr.options.usePureJavaScript&&vs.pbkdf2&&(i===null||typeof i!="object")&&(vs.pbkdf2Sync.length>4||!i||i==="sha1"))return typeof i!="string"&&(i="sha1"),r=Buffer.from(r,"binary"),e=Buffer.from(e,"binary"),s?vs.pbkdf2Sync.length===4?vs.pbkdf2(r,e,t,n,function(E,_){if(E)return s(E);s(null,_.toString("binary"))}):vs.pbkdf2(r,e,t,n,i,function(E,_){if(E)return s(E);s(null,_.toString("binary"))}):vs.pbkdf2Sync.length===4?vs.pbkdf2Sync(r,e,t,n).toString("binary"):vs.pbkdf2Sync(r,e,t,n,i).toString("binary");if((typeof i>"u"||i===null)&&(i="sha1"),typeof i=="string"){if(!(i in Kr.md.algorithms))throw new Error("Unknown hash algorithm: "+i);i=Kr.md[i].create()}var o=i.digestLength;if(n>4294967295*o){var a=new Error("Derived key is too long.");if(s)return s(a);throw a}var c=Math.ceil(n/o),u=n-(c-1)*o,l=Kr.hmac.create();l.start(i,r);var f="",h,d,p;if(!s){for(var m=1;m<=c;++m){l.start(null,null),l.update(e),l.update(Kr.util.int32ToBytes(m)),h=p=l.digest().getBytes();for(var g=2;g<=t;++g)l.start(null,null),l.update(p),d=l.digest().getBytes(),h=Kr.util.xorBytes(h,d,o),p=d;f+=mc)return s(null,f);l.start(null,null),l.update(e),l.update(Kr.util.int32ToBytes(m)),h=p=l.digest().getBytes(),g=2,b()}function b(){if(g<=t)return l.start(null,null),l.update(p),d=l.digest().getBytes(),h=Kr.util.xorBytes(h,d,o),p=d,++g,Kr.util.setImmediate(b);f+=m{var J0=Ve();Nt();var oE=aE.exports=J0.pem=J0.pem||{};oE.encode=function(r,e){e=e||{};var t="-----BEGIN "+r.type+`-----\r `,n;if(r.procType&&(n={name:"Proc-Type",values:[String(r.procType.version),r.procType.type]},t+=Z0(n)),r.contentDomain&&(n={name:"Content-Domain",values:[r.contentDomain]},t+=Z0(n)),r.dekInfo&&(n={name:"DEK-Info",values:[r.dekInfo.algorithm]},r.dekInfo.parameters&&n.values.push(r.dekInfo.parameters),t+=Z0(n)),r.headers)for(var i=0;i65&&o!==-1){var a=e[o];a===","?(++o,e=e.substr(0,o)+`\r `+e.substr(o)):e=e.substr(0,o)+`\r `+a+e.substr(o+1),s=i-o-1,o=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(o=i);return e}function VM(r){return r.replace(/^\s+/,"")}});var pE=B((nae,dE)=>{var Hi=Ve();ya();Nt();var lE=dE.exports=Hi.sha256=Hi.sha256||{};Hi.md.sha256=Hi.md.algorithms.sha256=lE;lE.create=function(){fE||qM();var r=null,e=Hi.util.createBuffer(),t=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),uE(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Hi.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(T3.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4,h5:r.h5,h6:r.h6,h7:r.h7};uE(f,t,i);var h=Hi.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},n};var T3=null,fE=!1,hE=null;function qM(){T3=String.fromCharCode(128),T3+=Hi.util.fillString(String.fromCharCode(0),64),hE=[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],fE=!0}function uE(r,e,t){for(var n,i,s,o,a,c,u,l,f,h,d,p,m,g,y,b=t.length();b>=64;){for(u=0;u<16;++u)e[u]=t.getInt32();for(;u<64;++u)n=e[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=e[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,e[u]=n+e[u-7]+i+e[u-16]|0;for(l=r.h0,f=r.h1,h=r.h2,d=r.h3,p=r.h4,m=r.h5,g=r.h6,y=r.h7,u=0;u<64;++u)o=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),a=g^p&(m^g),s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|h&(l^f),n=y+o+a+hE[u]+e[u],i=s+c,y=g,g=m,m=p,p=d+n>>>0,d=h,h=f,f=l,l=n+i>>>0;r.h0=r.h0+l|0,r.h1=r.h1+f|0,r.h2=r.h2+h|0,r.h3=r.h3+d|0,r.h4=r.h4+p|0,r.h5=r.h5+m|0,r.h6=r.h6+g|0,r.h7=r.h7+y|0,b-=64}}});var gE=B((iae,mE)=>{var Gi=Ve();Nt();var ed=null;Gi.util.isNodejs&&!Gi.options.usePureJavaScript&&!process.versions["node-webkit"]&&(ed=ba());var zM=mE.exports=Gi.prng=Gi.prng||{};zM.create=function(r){for(var e={plugin:r,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},t=r.md,n=new Array(32),i=0;i<32;++i)n[i]=t.create();e.pools=n,e.pool=0,e.generate=function(u,l){if(!l)return e.generateSync(u);var f=e.plugin.cipher,h=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed,m=Gi.util.createBuffer();e.key=null,g();function g(y){if(y)return l(y);if(m.length()>=u)return l(null,m.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return Gi.util.nextTick(function(){s(g)});var b=f(e.key,e.seed);e.generated+=b.length,m.putBytes(b),e.key=d(f(e.key,h(e.seed))),e.seed=p(f(e.key,e.seed)),Gi.util.setImmediate(g)}},e.generateSync=function(u){var l=e.plugin.cipher,f=e.plugin.increment,h=e.plugin.formatKey,d=e.plugin.formatSeed;e.key=null;for(var p=Gi.util.createBuffer();p.length()1048575&&(e.key=null),e.key===null&&o();var m=l(e.key,e.seed);e.generated+=m.length,p.putBytes(m),e.key=h(l(e.key,f(e.seed))),e.seed=d(l(e.key,e.seed))}return p.getBytes(u)};function s(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(f,h){if(f)return u(f);e.collect(h),a(),u()})}function o(){if(e.pools[0].messageLength>=32)return a();var u=32-e.pools[0].messageLength<<5;e.collect(e.seedFileSync(u)),a()}function a(){e.reseeds=e.reseeds===4294967295?0:e.reseeds+1;var u=e.plugin.md.create();u.update(e.keyBytes);for(var l=1,f=0;f<32;++f)e.reseeds%l===0&&(u.update(e.pools[f].digest().getBytes()),e.pools[f].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var h=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(h),e.generated=0}function c(u){var l=null,f=Gi.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(l=function(x){return h.getRandomValues(x)});var d=Gi.util.createBuffer();if(l)for(;d.length()>16),b+=(y&32767)<<16,b+=y>>15,b=(b&2147483647)+(b>>31),_=b&4294967295;for(var g=0;g<3;++g)E=_>>>(g<<3),E^=Math.floor(Math.random()*256),d.putByte(E&255)}return d.getBytes(u)}return ed?(e.seedFile=function(u,l){ed.randomBytes(u,function(f,h){if(f)return l(f);l(null,h.toString())})},e.seedFileSync=function(u){return ed.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,f=0;f>h&255);e.collect(f)},e.registerWorker=function(u){if(u===self)e.seedFile=function(f,h){function d(p){var m=p.data;m.forge&&m.forge.prng&&(self.removeEventListener("message",d),h(m.forge.prng.err,m.forge.prng.bytes))}self.addEventListener("message",d),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var h=f.data;h.forge&&h.forge.prng&&e.seedFile(h.forge.prng.needed,function(d,p){u.postMessage({forge:{prng:{err:d,bytes:p}}})})};u.addEventListener("message",l)}},e}});var $l=B((sae,D3)=>{var ur=Ve();Q0();pE();gE();Nt();(function(){if(ur.random&&ur.random.getBytes){D3.exports=ur.random;return}(function(r){var e={},t=new Array(4),n=ur.util.createBuffer();e.formatKey=function(f){var h=ur.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),ur.aes._expandKey(f,!1)},e.formatSeed=function(f){var h=ur.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},e.cipher=function(f,h){return ur.aes._updateBlock(f,h,t,!1),n.putInt32(t[0]),n.putInt32(t[1]),n.putInt32(t[2]),n.putInt32(t[3]),n.getBytes()},e.increment=function(f){return++f[3],f},e.md=ur.md.sha256;function i(){var f=ur.prng.create(e);return f.getBytes=function(h,d){return f.generate(h,d)},f.getBytesSync=function(h){return f.generate(h)},f}var s=i(),o=null,a=ur.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(o=function(f){return c.getRandomValues(f)}),ur.options.usePureJavaScript||!ur.util.isNodejs&&!o){if(typeof window>"u"||window.document,s.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}s.collect(u),u=null}r&&(r().mousemove(function(f){s.collectInt(f.clientX,16),s.collectInt(f.clientY,16)}),r().keypress(function(f){s.collectInt(f.charCode,8)}))}if(!ur.random)ur.random=s;else for(var l in s)ur.random[l]=s[l];ur.random.createInstance=i,D3.exports=ur.random})(typeof jQuery<"u"?jQuery:null)})()});var EE=B((oae,wE)=>{var jr=Ve();Nt();var C3=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],yE=[1,2,3,5],$M=function(r,e){return r<>16-e},HM=function(r,e){return(r&65535)>>e|r<<16-e&65535};wE.exports=jr.rc2=jr.rc2||{};jr.rc2.expandKey=function(r,e){typeof r=="string"&&(r=jr.util.createBuffer(r)),e=e||128;var t=r,n=r.length(),i=e,s=Math.ceil(i/8),o=255>>(i&7),a;for(a=n;a<128;a++)t.putByte(C3[t.at(a-1)+t.at(a-n)&255]);for(t.setAt(128-s,C3[t.at(128-s)&o]),a=127-s;a>=0;a--)t.setAt(a,C3[t.at(a+1)^t.at(a+s)]);return t};var bE=function(r,e,t){var n=!1,i=null,s=null,o=null,a,c,u,l,f=[];for(r=jr.rc2.expandKey(r,e),u=0;u<64;u++)f.push(r.getInt16Le());t?(a=function(p){for(u=0;u<4;u++)p[u]+=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),p[u]=$M(p[u],yE[u]),l++},c=function(p){for(u=0;u<4;u++)p[u]+=f[p[(u+3)%4]&63]}):(a=function(p){for(u=3;u>=0;u--)p[u]=HM(p[u],yE[u]),p[u]-=f[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),l--},c=function(p){for(u=3;u>=0;u--)p[u]-=f[p[(u+3)%4]&63]});var h=function(p){var m=[];for(u=0;u<4;u++){var g=i.getInt16Le();o!==null&&(t?g^=o.getInt16Le():o.putInt16Le(g)),m.push(g&65535)}l=t?0:63;for(var y=0;y=8;)h([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(p){var m=!0;if(t)if(p)m=p(8,i,!t);else{var g=i.length()===8?8:8-i.length();i.fillWithByte(g,g)}if(m&&(n=!0,d.update()),!t&&(m=i.length()===0,m))if(p)m=p(8,s,!t);else{var y=s.length(),b=s.at(y-1);b>y?m=!1:s.truncate(b)}return m}},d};jr.rc2.startEncrypting=function(r,e,t){var n=jr.rc2.createEncryptionCipher(r,128);return n.start(e,t),n};jr.rc2.createEncryptionCipher=function(r,e){return bE(r,e,!0)};jr.rc2.startDecrypting=function(r,e,t){var n=jr.rc2.createDecryptionCipher(r,128);return n.start(e,t),n};jr.rc2.createDecryptionCipher=function(r,e){return bE(r,e,!1)}});var Gl=B((aae,TE)=>{var P3=Ve();TE.exports=P3.jsbn=P3.jsbn||{};var _s,GM=0xdeadbeefcafe,xE=(GM&16777215)==15715070;function K(r,e,t){this.data=[],r!=null&&(typeof r=="number"?this.fromNumber(r,e,t):e==null&&typeof r!="string"?this.fromString(r,256):this.fromString(r,e))}P3.jsbn.BigInteger=K;function We(){return new K(null)}function WM(r,e,t,n,i,s){for(;--s>=0;){var o=e*this.data[r++]+t.data[n]+i;i=Math.floor(o/67108864),t.data[n++]=o&67108863}return i}function YM(r,e,t,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this.data[r]&32767,u=this.data[r++]>>15,l=a*c+u*o;c=o*c+((l&32767)<<15)+t.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),t.data[n++]=c&1073741823}return i}function vE(r,e,t,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this.data[r]&16383,u=this.data[r++]>>14,l=a*c+u*o;c=o*c+((l&16383)<<14)+t.data[n]+i,i=(c>>28)+(l>>14)+a*u,t.data[n++]=c&268435455}return i}typeof navigator>"u"?(K.prototype.am=vE,_s=28):xE&&navigator.appName=="Microsoft Internet Explorer"?(K.prototype.am=YM,_s=30):xE&&navigator.appName!="Netscape"?(K.prototype.am=WM,_s=26):(K.prototype.am=vE,_s=28);K.prototype.DB=_s;K.prototype.DM=(1<<_s)-1;K.prototype.DV=1<<_s;var k3=52;K.prototype.FV=Math.pow(2,k3);K.prototype.F1=k3-_s;K.prototype.F2=2*_s-k3;var QM="0123456789abcdefghijklmnopqrstuvwxyz",td=new Array,Ac,Kn;Ac="0".charCodeAt(0);for(Kn=0;Kn<=9;++Kn)td[Ac++]=Kn;Ac="a".charCodeAt(0);for(Kn=10;Kn<36;++Kn)td[Ac++]=Kn;Ac="A".charCodeAt(0);for(Kn=10;Kn<36;++Kn)td[Ac++]=Kn;function _E(r){return QM.charAt(r)}function SE(r,e){var t=td[r.charCodeAt(e)];return t??-1}function XM(r){for(var e=this.t-1;e>=0;--e)r.data[e]=this.data[e];r.t=this.t,r.s=this.s}function jM(r){this.t=1,this.s=r<0?-1:0,r>0?this.data[0]=r:r<-1?this.data[0]=r+this.DV:this.t=0}function ao(r){var e=We();return e.fromInt(r),e}function ZM(r,e){var t;if(e==16)t=4;else if(e==8)t=3;else if(e==256)t=8;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else{this.fromRadix(r,e);return}this.t=0,this.s=0;for(var n=r.length,i=!1,s=0;--n>=0;){var o=t==8?r[n]&255:SE(r,n);if(o<0){r.charAt(n)=="-"&&(i=!0);continue}i=!1,s==0?this.data[this.t++]=o:s+t>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB)}t==8&&r[0]&128&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==r;)--this.t}function eU(r){if(this.s<0)return"-"+this.negate().toString(r);var e;if(r==16)e=4;else if(r==8)e=3;else if(r==2)e=1;else if(r==32)e=5;else if(r==4)e=2;else return this.toRadix(r);var t=(1<0)for(a>a)>0&&(i=!0,s=_E(n));o>=0;)a>(a+=this.DB-e)):(n=this.data[o]>>(a-=e)&t,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=_E(n));return i?s:"0"}function tU(){var r=We();return K.ZERO.subTo(this,r),r}function rU(){return this.s<0?this.negate():this}function nU(r){var e=this.s-r.s;if(e!=0)return e;var t=this.t;if(e=t-r.t,e!=0)return this.s<0?-e:e;for(;--t>=0;)if((e=this.data[t]-r.data[t])!=0)return e;return 0}function rd(r){var e=1,t;return(t=r>>>16)!=0&&(r=t,e+=16),(t=r>>8)!=0&&(r=t,e+=8),(t=r>>4)!=0&&(r=t,e+=4),(t=r>>2)!=0&&(r=t,e+=2),(t=r>>1)!=0&&(r=t,e+=1),e}function iU(){return this.t<=0?0:this.DB*(this.t-1)+rd(this.data[this.t-1]^this.s&this.DM)}function sU(r,e){var t;for(t=this.t-1;t>=0;--t)e.data[t+r]=this.data[t];for(t=r-1;t>=0;--t)e.data[t]=0;e.t=this.t+r,e.s=this.s}function oU(r,e){for(var t=r;t=0;--a)e.data[a+s+1]=this.data[a]>>n|o,o=(this.data[a]&i)<=0;--a)e.data[a]=0;e.data[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp()}function cU(r,e){e.s=this.s;var t=Math.floor(r/this.DB);if(t>=this.t){e.t=0;return}var n=r%this.DB,i=this.DB-n,s=(1<>n;for(var o=t+1;o>n;n>0&&(e.data[this.t-t-1]|=(this.s&s)<>=this.DB;if(r.t>=this.DB;n+=this.s}else{for(n+=this.s;t>=this.DB;n-=r.s}e.s=n<0?-1:0,n<-1?e.data[t++]=this.DV+n:n>0&&(e.data[t++]=n),e.t=t,e.clamp()}function lU(r,e){var t=this.abs(),n=r.abs(),i=t.t;for(e.t=i+n.t;--i>=0;)e.data[i]=0;for(i=0;i=0;)r.data[t]=0;for(t=0;t=e.DV&&(r.data[t+e.t]-=e.DV,r.data[t+e.t+1]=1)}r.t>0&&(r.data[r.t-1]+=e.am(t,e.data[t],r,2*t,0,1)),r.s=0,r.clamp()}function hU(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,s),i.lShiftTo(c,t)):(n.copyTo(s),i.copyTo(t));var u=s.t,l=s.data[u-1];if(l!=0){var f=l*(1<1?s.data[u-2]>>this.F2:0),h=this.FV/f,d=(1<=0&&(t.data[t.t++]=1,t.subTo(y,t)),K.ONE.dlShiftTo(u,y),y.subTo(s,s);s.t=0;){var b=t.data[--m]==l?this.DM:Math.floor(t.data[m]*h+(t.data[m-1]+p)*d);if((t.data[m]+=s.am(0,b,t,g,0,u))0&&t.rShiftTo(c,t),o<0&&K.ZERO.subTo(t,t)}}}function dU(r){var e=We();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(K.ZERO)>0&&r.subTo(e,e),e}function wa(r){this.m=r}function pU(r){return r.s<0||r.compareTo(this.m)>=0?r.mod(this.m):r}function mU(r){return r}function gU(r){r.divRemTo(this.m,null,r)}function yU(r,e,t){r.multiplyTo(e,t),this.reduce(t)}function bU(r,e){r.squareTo(e),this.reduce(e)}wa.prototype.convert=pU;wa.prototype.revert=mU;wa.prototype.reduce=gU;wa.prototype.mulTo=yU;wa.prototype.sqrTo=bU;function wU(){if(this.t<1)return 0;var r=this.data[0];if(!(r&1))return 0;var e=r&3;return e=e*(2-(r&15)*e)&15,e=e*(2-(r&255)*e)&255,e=e*(2-((r&65535)*e&65535))&65535,e=e*(2-r*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Ea(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(e,e),e}function xU(r){var e=We();return r.copyTo(e),this.reduce(e),e}function vU(r){for(;r.t<=this.mt2;)r.data[r.t++]=0;for(var e=0;e>15)*this.mpl&this.um)<<15)&r.DM;for(t=e+this.m.t,r.data[t]+=this.m.am(0,n,r,e,0,this.m.t);r.data[t]>=r.DV;)r.data[t]-=r.DV,r.data[++t]++}r.clamp(),r.drShiftTo(this.m.t,r),r.compareTo(this.m)>=0&&r.subTo(this.m,r)}function _U(r,e){r.squareTo(e),this.reduce(e)}function SU(r,e,t){r.multiplyTo(e,t),this.reduce(t)}Ea.prototype.convert=EU;Ea.prototype.revert=xU;Ea.prototype.reduce=vU;Ea.prototype.mulTo=SU;Ea.prototype.sqrTo=_U;function RU(){return(this.t>0?this.data[0]&1:this.s)==0}function IU(r,e){if(r>4294967295||r<1)return K.ONE;var t=We(),n=We(),i=e.convert(this),s=rd(r)-1;for(i.copyTo(t);--s>=0;)if(e.sqrTo(t,n),(r&1<0)e.mulTo(n,i,t);else{var o=t;t=n,n=o}return e.revert(t)}function AU(r,e){var t;return r<256||e.isEven()?t=new wa(e):t=new Ea(e),this.exp(r,t)}K.prototype.copyTo=XM;K.prototype.fromInt=jM;K.prototype.fromString=ZM;K.prototype.clamp=JM;K.prototype.dlShiftTo=sU;K.prototype.drShiftTo=oU;K.prototype.lShiftTo=aU;K.prototype.rShiftTo=cU;K.prototype.subTo=uU;K.prototype.multiplyTo=lU;K.prototype.squareTo=fU;K.prototype.divRemTo=hU;K.prototype.invDigit=wU;K.prototype.isEven=RU;K.prototype.exp=IU;K.prototype.toString=eU;K.prototype.negate=tU;K.prototype.abs=rU;K.prototype.compareTo=nU;K.prototype.bitLength=iU;K.prototype.mod=dU;K.prototype.modPowInt=AU;K.ZERO=ao(0);K.ONE=ao(1);function TU(){var r=We();return this.copyTo(r),r}function DU(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function PU(){return this.t==0?this.s:this.data[0]<<16>>16}function kU(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function NU(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function OU(r){if(r==null&&(r=10),this.signum()==0||r<2||r>36)return"0";var e=this.chunkSize(r),t=Math.pow(r,e),n=ao(t),i=We(),s=We(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(t+s.intValue()).toString(r).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(r)+o}function BU(r,e){this.fromInt(0),e==null&&(e=10);for(var t=this.chunkSize(e),n=Math.pow(e,t),i=!1,s=0,o=0,a=0;a=t&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(o,0)),i&&K.ZERO.subTo(this,this)}function LU(r,e,t){if(typeof e=="number")if(r<2)this.fromInt(1);else for(this.fromNumber(r,t),this.testBit(r-1)||this.bitwiseTo(K.ONE.shiftLeft(r-1),N3,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>r&&this.subTo(K.ONE.shiftLeft(r-1),this);else{var n=new Array,i=r&7;n.length=(r>>3)+1,e.nextBytes(n),i>0?n[0]&=(1<0)for(t>t)!=(this.s&this.DM)>>t&&(e[i++]=n|this.s<=0;)t<8?(n=(this.data[r]&(1<>(t+=this.DB-8)):(n=this.data[r]>>(t-=8)&255,t<=0&&(t+=this.DB,--r)),n&128&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function UU(r){return this.compareTo(r)==0}function FU(r){return this.compareTo(r)<0?this:r}function KU(r){return this.compareTo(r)>0?this:r}function VU(r,e,t){var n,i,s=Math.min(r.t,this.t);for(n=0;n>=16,e+=16),r&255||(r>>=8,e+=8),r&15||(r>>=4,e+=4),r&3||(r>>=2,e+=2),r&1||++e,e}function jU(){for(var r=0;r=this.t?this.s!=0:(this.data[e]&1<>=this.DB;if(r.t>=this.DB;n+=this.s}else{for(n+=this.s;t>=this.DB;n+=r.s}e.s=n<0?-1:0,n>0?e.data[t++]=n:n<-1&&(e.data[t++]=this.DV+n),e.t=t,e.clamp()}function oF(r){var e=We();return this.addTo(r,e),e}function aF(r){var e=We();return this.subTo(r,e),e}function cF(r){var e=We();return this.multiplyTo(r,e),e}function uF(r){var e=We();return this.divRemTo(r,e,null),e}function lF(r){var e=We();return this.divRemTo(r,null,e),e}function fF(r){var e=We(),t=We();return this.divRemTo(r,e,t),new Array(e,t)}function hF(r){this.data[this.t]=this.am(0,r-1,this,0,0,this.t),++this.t,this.clamp()}function dF(r,e){if(r!=0){for(;this.t<=e;)this.data[this.t++]=0;for(this.data[e]+=r;this.data[e]>=this.DV;)this.data[e]-=this.DV,++e>=this.t&&(this.data[this.t++]=0),++this.data[e]}}function Hl(){}function AE(r){return r}function pF(r,e,t){r.multiplyTo(e,t)}function mF(r,e){r.squareTo(e)}Hl.prototype.convert=AE;Hl.prototype.revert=AE;Hl.prototype.mulTo=pF;Hl.prototype.sqrTo=mF;function gF(r){return this.exp(r,new Hl)}function yF(r,e,t){var n=Math.min(this.t+r.t,e);for(t.s=0,t.t=n;n>0;)t.data[--n]=0;var i;for(i=t.t-this.t;n=0;)t.data[n]=0;for(n=Math.max(e-this.t,0);n2*this.m.t)return r.mod(this.m);if(r.compareTo(this.m)<0)return r;var e=We();return r.copyTo(e),this.reduce(e),e}function EF(r){return r}function xF(r){for(r.drShiftTo(this.m.t-1,this.r2),r.t>this.m.t+1&&(r.t=this.m.t+1,r.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);r.compareTo(this.r2)<0;)r.dAddOffset(1,this.m.t+1);for(r.subTo(this.r2,r);r.compareTo(this.m)>=0;)r.subTo(this.m,r)}function vF(r,e){r.squareTo(e),this.reduce(e)}function _F(r,e,t){r.multiplyTo(e,t),this.reduce(t)}Tc.prototype.convert=wF;Tc.prototype.revert=EF;Tc.prototype.reduce=xF;Tc.prototype.mulTo=_F;Tc.prototype.sqrTo=vF;function SF(r,e){var t=r.bitLength(),n,i=ao(1),s;if(t<=0)return i;t<18?n=1:t<48?n=3:t<144?n=4:t<768?n=5:n=6,t<8?s=new wa(e):e.isEven()?s=new Tc(e):s=new Ea(e);var o=new Array,a=3,c=n-1,u=(1<1){var l=We();for(s.sqrTo(o[1],l);a<=u;)o[a]=We(),s.mulTo(l,o[a-2],o[a]),a+=2}var f=r.t-1,h,d=!0,p=We(),m;for(t=rd(r.data[f])-1;f>=0;){for(t>=c?h=r.data[f]>>t-c&u:(h=(r.data[f]&(1<0&&(h|=r.data[f-1]>>this.DB+t-c)),a=n;!(h&1);)h>>=1,--a;if((t-=a)<0&&(t+=this.DB,--f),d)o[h].copyTo(i),d=!1;else{for(;a>1;)s.sqrTo(i,p),s.sqrTo(p,i),a-=2;a>0?s.sqrTo(i,p):(m=i,i=p,p=m),s.mulTo(p,o[h],i)}for(;f>=0&&!(r.data[f]&1<0&&(e.rShiftTo(s,e),t.rShiftTo(s,t));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),e.compareTo(t)>=0?(e.subTo(t,e),e.rShiftTo(1,e)):(t.subTo(e,t),t.rShiftTo(1,t));return s>0&&t.lShiftTo(s,t),t}function IF(r){if(r<=0)return 0;var e=this.DV%r,t=this.s<0?r-1:0;if(this.t>0)if(e==0)t=this.data[0]%r;else for(var n=this.t-1;n>=0;--n)t=(e*t+this.data[n])%r;return t}function AF(r){var e=r.isEven();if(this.isEven()&&e||r.signum()==0)return K.ZERO;for(var t=r.clone(),n=this.clone(),i=ao(1),s=ao(0),o=ao(0),a=ao(1);t.signum()!=0;){for(;t.isEven();)t.rShiftTo(1,t),e?((!i.isEven()||!s.isEven())&&(i.addTo(this,i),s.subTo(r,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(r,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),e?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(r,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(r,a),a.rShiftTo(1,a);t.compareTo(n)>=0?(t.subTo(n,t),e&&i.subTo(o,i),s.subTo(a,s)):(n.subTo(t,n),e&&o.subTo(i,o),a.subTo(s,a))}if(n.compareTo(K.ONE)!=0)return K.ZERO;if(a.compareTo(r)>=0)return a.subtract(r);if(a.signum()<0)a.addTo(r,a);else return a;return a.signum()<0?a.add(r):a}var pi=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],TF=(1<<26)/pi[pi.length-1];function DF(r){var e,t=this.abs();if(t.t==1&&t.data[0]<=pi[pi.length-1]){for(e=0;e=0);var a=s.modPow(n,this);if(a.compareTo(K.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++{var Wi=Ve();ya();Nt();var CE=kE.exports=Wi.sha1=Wi.sha1||{};Wi.md.sha1=Wi.md.algorithms.sha1=CE;CE.create=function(){PE||kF();var r=null,e=Wi.util.createBuffer(),t=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),DE(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Wi.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(O3.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4};DE(f,t,i);var h=Wi.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},n};var O3=null,PE=!1;function kF(){O3=String.fromCharCode(128),O3+=Wi.util.fillString(String.fromCharCode(0),64),PE=!0}function DE(r,e,t){for(var n,i,s,o,a,c,u,l,f=t.length();f>=64;){for(i=r.h0,s=r.h1,o=r.h2,a=r.h3,c=r.h4,l=0;l<16;++l)n=t.getInt32(),e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<20;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<32;++l)n=e[l-3]^e[l-8]^e[l-14]^e[l-16],n=n<<1|n>>>31,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<40;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<60;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s&o|a&(s^o),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<80;++l)n=e[l-6]^e[l-16]^e[l-28]^e[l-32],n=n<<2|n>>>30,e[l]=n,u=s^o^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;r.h0=r.h0+i|0,r.h1=r.h1+s|0,r.h2=r.h2+o|0,r.h3=r.h3+a|0,r.h4=r.h4+c|0,f-=64}}});var LE=B((uae,BE)=>{var Yi=Ve();Nt();$l();NE();var OE=BE.exports=Yi.pkcs1=Yi.pkcs1||{};OE.encode_rsa_oaep=function(r,e,t){var n,i,s,o;typeof t=="string"?(n=t,i=arguments[3]||void 0,s=arguments[4]||void 0):t&&(n=t.label||void 0,i=t.seed||void 0,s=t.md||void 0,t.mgf1&&t.mgf1.md&&(o=t.mgf1.md)),s?s.start():s=Yi.md.sha1.create(),o||(o=s);var a=Math.ceil(r.n.bitLength()/8),c=a-2*s.digestLength-2;if(e.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=e.length,u.maxLength=c,u}n||(n=""),s.update(n,"raw");for(var l=s.digest(),f="",h=c-e.length,d=0;d>24&255,s>>16&255,s>>8&255,s&255);t.start(),t.update(r+o),n+=t.digest().getBytes()}return n.substring(0,e)}});var ME=B((lae,B3)=>{var co=Ve();Nt();Gl();$l();(function(){if(co.prime){B3.exports=co.prime;return}var r=B3.exports=co.prime=co.prime||{},e=co.jsbn.BigInteger,t=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(f,h){return f|h};r.generateProbablePrime=function(f,h,d){typeof h=="function"&&(d=h,h={}),h=h||{};var p=h.algorithm||"PRIMEINC";typeof p=="string"&&(p={name:p}),p.options=p.options||{};var m=h.prng||co.random,g={nextBytes:function(y){for(var b=m.getBytesSync(y.length),E=0;Eh&&(f=u(h,d)),f.isProbablePrime(m))return y(null,f);f.dAddOffset(t[p++%8],0)}while(g<0||+new Date-b"u")return o(f,h,d,p);var m=u(f,h),g=d.workers,y=d.workLoad||100,b=y*30/8,E=d.workerScript||"forge/prime.worker.js";if(g===-1)return co.util.estimateCores(function(x,v){x&&(v=2),g=v-1,_()});_();function _(){g=Math.max(1,g);for(var x=[],v=0;vf&&(m=u(f,h));var te=m.toString(16);q.target.postMessage({hex:te,workLoad:y}),m.dAddOffset(b,0)}}}}function u(f,h){var d=new e(f,h),p=f-1;return d.testBit(p)||d.bitwiseTo(e.ONE.shiftLeft(p),i,d),d.dAddOffset(31-d.mod(n).byteValue(),0),d}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var Dc=B((fae,$E)=>{var ye=Ve();ma();Gl();$0();LE();ME();$l();Nt();typeof qe>"u"&&(qe=ye.jsbn.BigInteger);var qe,L3=ye.util.isNodejs?ba():null,D=ye.asn1,Vn=ye.util;ye.pki=ye.pki||{};$E.exports=ye.pki.rsa=ye.rsa=ye.rsa||{};var De=ye.pki,NF=[6,4,2,4,2,4,6,2],OF={name:"PrivateKeyInfo",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:D.Class.UNIVERSAL,type:D.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:D.Class.UNIVERSAL,type:D.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},BF={name:"RSAPrivateKey",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},LF={name:"RSAPublicKey",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:D.Class.UNIVERSAL,type:D.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},MF=ye.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:D.Class.UNIVERSAL,type:D.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:D.Class.UNIVERSAL,type:D.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},UF={name:"DigestInfo",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:D.Class.UNIVERSAL,type:D.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:D.Class.UNIVERSAL,type:D.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:D.Class.UNIVERSAL,type:D.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:D.Class.UNIVERSAL,type:D.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},FF=function(r){var e;if(r.algorithm in De.oids)e=De.oids[r.algorithm];else{var t=new Error("Unknown message digest algorithm.");throw t.algorithm=r.algorithm,t}var n=D.oidToDer(e).getBytes(),i=D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[]),s=D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[]);s.value.push(D.create(D.Class.UNIVERSAL,D.Type.OID,!1,n)),s.value.push(D.create(D.Class.UNIVERSAL,D.Type.NULL,!1,""));var o=D.create(D.Class.UNIVERSAL,D.Type.OCTETSTRING,!1,r.digest().getBytes());return i.value.push(s),i.value.push(o),D.toDer(i).getBytes()},qE=function(r,e,t){if(t)return r.modPow(e.e,e.n);if(!e.p||!e.q)return r.modPow(e.d,e.n);e.dP||(e.dP=e.d.mod(e.p.subtract(qe.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(qe.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new qe(ye.util.bytesToHex(ye.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(qe.ONE));r=r.multiply(n.modPow(e.e,e.n)).mod(e.n);for(var i=r.mod(e.p).modPow(e.dP,e.p),s=r.mod(e.q).modPow(e.dQ,e.q);i.compareTo(s)<0;)i=i.add(e.p);var o=i.subtract(s).multiply(e.qInv).mod(e.p).multiply(e.q).add(s);return o=o.multiply(n.modInverse(e.n)).mod(e.n),o};De.rsa.encrypt=function(r,e,t){var n=t,i,s=Math.ceil(e.n.bitLength()/8);t!==!1&&t!==!0?(n=t===2,i=zE(r,e,t)):(i=ye.util.createBuffer(),i.putBytes(r));for(var o=new qe(i.toHex(),16),a=qE(o,e,n),c=a.toString(16),u=ye.util.createBuffer(),l=s-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(ye.util.hexToBytes(c)),u.getBytes()};De.rsa.decrypt=function(r,e,t,n){var i=Math.ceil(e.n.bitLength()/8);if(r.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=r.length,s.expected=i,s}var o=new qe(ye.util.createBuffer(r).toHex(),16);if(o.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=qE(o,e,t),c=a.toString(16),u=ye.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(ye.util.hexToBytes(c)),n!==!1?id(u.getBytes(),e,t):u.getBytes()};De.rsa.createKeyPairGenerationState=function(r,e,t){typeof r=="string"&&(r=parseInt(r,10)),r=r||2048,t=t||{};var n=t.prng||ye.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u>1,pBits:r-(r>>1),pqState:0,num:null,keys:null},o.e.fromInt(o.eInt);else throw new Error("Invalid key generation algorithm: "+s);return o};De.rsa.stepKeyPairGenerationState=function(r,e){"algorithm"in r||(r.algorithm="PRIMEINC");var t=new qe(null);t.fromInt(30);for(var n=0,i=function(f,h){return f|h},s=+new Date,o,a=0;r.keys===null&&(e<=0||ac?r.pqState=0:r.num.isProbablePrime(VF(r.num.bitLength()))?++r.pqState:r.num.dAddOffset(NF[n++%8],0):r.pqState===2?r.pqState=r.num.subtract(qe.ONE).gcd(r.e).compareTo(qe.ONE)===0?3:0:r.pqState===3&&(r.pqState=0,r.p===null?r.p=r.num:r.q=r.num,r.p!==null&&r.q!==null&&++r.state,r.num=null)}else if(r.state===1)r.p.compareTo(r.q)<0&&(r.num=r.p,r.p=r.q,r.q=r.num),++r.state;else if(r.state===2)r.p1=r.p.subtract(qe.ONE),r.q1=r.q.subtract(qe.ONE),r.phi=r.p1.multiply(r.q1),++r.state;else if(r.state===3)r.phi.gcd(r.e).compareTo(qe.ONE)===0?++r.state:(r.p=null,r.q=null,r.state=0);else if(r.state===4)r.n=r.p.multiply(r.q),r.n.bitLength()===r.bits?++r.state:(r.q=null,r.state=0);else if(r.state===5){var l=r.e.modInverse(r.phi);r.keys={privateKey:De.rsa.setPrivateKey(r.n,r.e,l,r.p,r.q,l.mod(r.p1),l.mod(r.q1),r.q.modInverse(r.p)),publicKey:De.rsa.setPublicKey(r.n,r.e)}}o=+new Date,a+=o-s,s=o}return r.keys!==null};De.rsa.generateKeyPair=function(r,e,t,n){if(arguments.length===1?typeof r=="object"?(t=r,r=void 0):typeof r=="function"&&(n=r,r=void 0):arguments.length===2?typeof r=="number"?typeof e=="function"?(n=e,e=void 0):typeof e!="number"&&(t=e,e=void 0):(t=r,n=e,r=void 0,e=void 0):arguments.length===3&&(typeof e=="number"?typeof t=="function"&&(n=t,t=void 0):(n=t,t=e,e=void 0)),t=t||{},r===void 0&&(r=t.bits||2048),e===void 0&&(e=t.e||65537),!ye.options.usePureJavaScript&&!t.prng&&r>=256&&r<=16384&&(e===65537||e===3)){if(n){if(UE("generateKeyPair"))return L3.generateKeyPair("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:De.privateKeyFromPem(u),publicKey:De.publicKeyFromPem(c)})});if(FE("generateKey")&&FE("exportKey"))return Vn.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:VE(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return Vn.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=De.privateKeyFromAsn1(D.fromDer(ye.util.createBuffer(a)));n(null,{privateKey:c,publicKey:De.setRsaPublicKey(c.n,c.e)})}});if(KE("generateKey")&&KE("exportKey")){var i=Vn.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:VE(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=Vn.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,h=De.privateKeyFromAsn1(D.fromDer(ye.util.createBuffer(f)));n(null,{privateKey:h,publicKey:De.setRsaPublicKey(h.n,h.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(UE("generateKeyPairSync")){var s=L3.generateKeyPairSync("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:De.privateKeyFromPem(s.privateKey),publicKey:De.publicKeyFromPem(s.publicKey)}}}var o=De.rsa.createKeyPairGenerationState(r,e,t);if(!n)return De.rsa.stepKeyPairGenerationState(o,0),o.keys;KF(o,t,n)};De.setRsaPublicKey=De.rsa.setPublicKey=function(r,e){var t={n:r,e};return t.encrypt=function(n,i,s){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return zE(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return ye.pkcs1.encode_rsa_oaep(c,a,s)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var o=i.encode(n,t,!0);return De.rsa.encrypt(o,t,!0)},t.verify=function(n,i,s,o){typeof s=="string"?s=s.toUpperCase():s===void 0&&(s="RSASSA-PKCS1-V1_5"),o===void 0&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),s==="RSASSA-PKCS1-V1_5"?s={verify:function(c,u){u=id(u,t,!0);var l=D.fromDer(u,{parseAllBytes:o._parseAllDigestBytes}),f={},h=[];if(!D.validate(l,UF,f,h)){var d=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw d.errors=h,d}var p=D.derToOid(f.algorithmIdentifier);if(!(p===ye.oids.md2||p===ye.oids.md5||p===ye.oids.sha1||p===ye.oids.sha224||p===ye.oids.sha256||p===ye.oids.sha384||p===ye.oids.sha512||p===ye.oids["sha512-224"]||p===ye.oids["sha512-256"])){var d=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw d.oid=p,d}if((p===ye.oids.md2||p===ye.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(s==="NONE"||s==="NULL"||s===null)&&(s={verify:function(c,u){return u=id(u,t,!0),c===u}});var a=De.rsa.decrypt(i,t,!0,!1);return s.verify(n,a,t.n.bitLength())},t};De.setRsaPrivateKey=De.rsa.setPrivateKey=function(r,e,t,n,i,s,o,a){var c={n:r,e,d:t,p:n,q:i,dP:s,dQ:o,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var h=De.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:id};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(d,p){return ye.pkcs1.decode_rsa_oaep(p,d,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(d){return d}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(h,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:FF},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var h=l.encode(u,c.n.bitLength());return De.rsa.encrypt(h,c,f)},c};De.wrapRsaPrivateKey=function(r){return D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,D.integerToDer(0).getBytes()),D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[D.create(D.Class.UNIVERSAL,D.Type.OID,!1,D.oidToDer(De.oids.rsaEncryption).getBytes()),D.create(D.Class.UNIVERSAL,D.Type.NULL,!1,"")]),D.create(D.Class.UNIVERSAL,D.Type.OCTETSTRING,!1,D.toDer(r).getBytes())])};De.privateKeyFromAsn1=function(r){var e={},t=[];if(D.validate(r,OF,e,t)&&(r=D.fromDer(ye.util.createBuffer(e.privateKey))),e={},t=[],!D.validate(r,BF,e,t)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=t,n}var i,s,o,a,c,u,l,f;return i=ye.util.createBuffer(e.privateKeyModulus).toHex(),s=ye.util.createBuffer(e.privateKeyPublicExponent).toHex(),o=ye.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=ye.util.createBuffer(e.privateKeyPrime1).toHex(),c=ye.util.createBuffer(e.privateKeyPrime2).toHex(),u=ye.util.createBuffer(e.privateKeyExponent1).toHex(),l=ye.util.createBuffer(e.privateKeyExponent2).toHex(),f=ye.util.createBuffer(e.privateKeyCoefficient).toHex(),De.setRsaPrivateKey(new qe(i,16),new qe(s,16),new qe(o,16),new qe(a,16),new qe(c,16),new qe(u,16),new qe(l,16),new qe(f,16))};De.privateKeyToAsn1=De.privateKeyToRSAPrivateKey=function(r){return D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,D.integerToDer(0).getBytes()),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.n)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.e)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.d)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.p)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.q)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.dP)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.dQ)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.qInv))])};De.publicKeyFromAsn1=function(r){var e={},t=[];if(D.validate(r,MF,e,t)){var n=D.derToOid(e.publicKeyOid);if(n!==De.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}r=e.rsaPublicKey}if(t=[],!D.validate(r,LF,e,t)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=t,i}var s=ye.util.createBuffer(e.publicKeyModulus).toHex(),o=ye.util.createBuffer(e.publicKeyExponent).toHex();return De.setRsaPublicKey(new qe(s,16),new qe(o,16))};De.publicKeyToAsn1=De.publicKeyToSubjectPublicKeyInfo=function(r){return D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[D.create(D.Class.UNIVERSAL,D.Type.OID,!1,D.oidToDer(De.oids.rsaEncryption).getBytes()),D.create(D.Class.UNIVERSAL,D.Type.NULL,!1,"")]),D.create(D.Class.UNIVERSAL,D.Type.BITSTRING,!1,[De.publicKeyToRSAPublicKey(r)])])};De.publicKeyToRSAPublicKey=function(r){return D.create(D.Class.UNIVERSAL,D.Type.SEQUENCE,!0,[D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.n)),D.create(D.Class.UNIVERSAL,D.Type.INTEGER,!1,Qi(r.e))])};function zE(r,e,t){var n=ye.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(r.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=r.length,s.max=i-11,s}n.putByte(0),n.putByte(t);var o=i-3-r.length,a;if(t===0||t===1){a=t===0?0:255;for(var c=0;c0;){for(var u=0,l=ye.random.getBytes(o),c=0;c"u")throw new Error("Encryption block is invalid.");var c=0;if(a===0){c=i-3-n;for(var u=0;u1;){if(s.getByte()!==255){--s.read;break}++c}else if(a===2)for(c=0;s.length()>1;){if(s.getByte()===0){--s.read;break}++c}var l=s.getByte();if(l!==0||c!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function KF(r,e,t){typeof e=="function"&&(t=e,e={}),e=e||{};var n={algorithm:{name:e.algorithm||"PRIMEINC",options:{workers:e.workers||2,workLoad:e.workLoad||100,workerScript:e.workerScript}}};"prng"in e&&(n.prng=e.prng),i();function i(){s(r.pBits,function(a,c){if(a)return t(a);if(r.p=c,r.q!==null)return o(a,r.q);s(r.qBits,o)})}function s(a,c){ye.prime.generateProbablePrime(a,n,c)}function o(a,c){if(a)return t(a);if(r.q=c,r.p.compareTo(r.q)<0){var u=r.p;r.p=r.q,r.q=u}if(r.p.subtract(qe.ONE).gcd(r.e).compareTo(qe.ONE)!==0){r.p=null,i();return}if(r.q.subtract(qe.ONE).gcd(r.e).compareTo(qe.ONE)!==0){r.q=null,s(r.qBits,o);return}if(r.p1=r.p.subtract(qe.ONE),r.q1=r.q.subtract(qe.ONE),r.phi=r.p1.multiply(r.q1),r.phi.gcd(r.e).compareTo(qe.ONE)!==0){r.p=r.q=null,i();return}if(r.n=r.p.multiply(r.q),r.n.bitLength()!==r.bits){r.q=null,s(r.qBits,o);return}var l=r.e.modInverse(r.phi);r.keys={privateKey:De.rsa.setPrivateKey(r.n,r.e,l,r.p,r.q,l.mod(r.p1),l.mod(r.q1),r.q.modInverse(r.p)),publicKey:De.rsa.setPublicKey(r.n,r.e)},t(null,r.keys)}}function Qi(r){var e=r.toString(16);e[0]>="8"&&(e="00"+e);var t=ye.util.hexToBytes(e);return t.length>1&&(t.charCodeAt(0)===0&&!(t.charCodeAt(1)&128)||t.charCodeAt(0)===255&&(t.charCodeAt(1)&128)===128)?t.substr(1):t}function VF(r){return r<=100?27:r<=150?18:r<=200?15:r<=250?12:r<=300?9:r<=350?8:r<=400?7:r<=500?6:r<=600?5:r<=800?4:r<=1250?3:2}function UE(r){return ye.util.isNodejs&&typeof L3[r]=="function"}function FE(r){return typeof Vn.globalScope<"u"&&typeof Vn.globalScope.crypto=="object"&&typeof Vn.globalScope.crypto.subtle=="object"&&typeof Vn.globalScope.crypto.subtle[r]=="function"}function KE(r){return typeof Vn.globalScope<"u"&&typeof Vn.globalScope.msCrypto=="object"&&typeof Vn.globalScope.msCrypto.subtle=="object"&&typeof Vn.globalScope.msCrypto.subtle[r]=="function"}function VE(r){for(var e=ye.util.hexToBytes(r.toString(16)),t=new Uint8Array(e.length),n=0;n{var ie=Ve();Q0();ma();tE();ya();$0();A3();cE();$l();EE();Dc();Nt();typeof HE>"u"&&(HE=ie.jsbn.BigInteger);var HE,N=ie.asn1,Pe=ie.pki=ie.pki||{};QE.exports=Pe.pbe=ie.pbe=ie.pbe||{};var xa=Pe.oids,qF={name:"EncryptedPrivateKeyInfo",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:N.Class.UNIVERSAL,type:N.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},zF={name:"PBES2Algorithms",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:N.Class.UNIVERSAL,type:N.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:N.Class.UNIVERSAL,type:N.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:N.Class.UNIVERSAL,type:N.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},$F={name:"pkcs-12PbeParams",tagClass:N.Class.UNIVERSAL,type:N.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:N.Class.UNIVERSAL,type:N.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:N.Class.UNIVERSAL,type:N.Type.INTEGER,constructed:!1,capture:"iterations"}]};Pe.encryptPrivateKeyInfo=function(r,e,t){t=t||{},t.saltSize=t.saltSize||8,t.count=t.count||2048,t.algorithm=t.algorithm||"aes128",t.prfAlgorithm=t.prfAlgorithm||"sha1";var n=ie.random.getBytesSync(t.saltSize),i=t.count,s=N.integerToDer(i),o,a,c;if(t.algorithm.indexOf("aes")===0||t.algorithm==="des"){var u,l,f;switch(t.algorithm){case"aes128":o=16,u=16,l=xa["aes128-CBC"],f=ie.aes.createEncryptionCipher;break;case"aes192":o=24,u=16,l=xa["aes192-CBC"],f=ie.aes.createEncryptionCipher;break;case"aes256":o=32,u=16,l=xa["aes256-CBC"],f=ie.aes.createEncryptionCipher;break;case"des":o=8,u=8,l=xa.desCBC,f=ie.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=t.algorithm,h}var d="hmacWith"+t.prfAlgorithm.toUpperCase(),p=YE(d),m=ie.pkcs5.pbkdf2(e,n,i,o,p),g=ie.random.getBytesSync(u),y=f(m);y.start(g),y.update(N.toDer(r)),y.finish(),c=y.output.getBytes();var b=HF(n,s,o,d);a=N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OID,!1,N.oidToDer(xa.pkcs5PBES2).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OID,!1,N.oidToDer(xa.pkcs5PBKDF2).getBytes()),b]),N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OID,!1,N.oidToDer(l).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.OCTETSTRING,!1,g)])])])}else if(t.algorithm==="3des"){o=24;var E=new ie.util.ByteBuffer(n),m=Pe.pbe.generatePkcs12Key(e,E,1,i,o),g=Pe.pbe.generatePkcs12Key(e,E,2,i,o),y=ie.des.createEncryptionCipher(m);y.start(g),y.update(N.toDer(r)),y.finish(),c=y.output.getBytes(),a=N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OID,!1,N.oidToDer(xa["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[N.create(N.Class.UNIVERSAL,N.Type.OCTETSTRING,!1,n),N.create(N.Class.UNIVERSAL,N.Type.INTEGER,!1,s.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=t.algorithm,h}var _=N.create(N.Class.UNIVERSAL,N.Type.SEQUENCE,!0,[a,N.create(N.Class.UNIVERSAL,N.Type.OCTETSTRING,!1,c)]);return _};Pe.decryptPrivateKeyInfo=function(r,e){var t=null,n={},i=[];if(!N.validate(r,qF,n,i)){var s=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=N.derToOid(n.encryptionOid),a=Pe.pbe.getCipher(o,n.encryptionParams,e),c=ie.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(t=N.fromDer(a.output)),t};Pe.encryptedPrivateKeyToPem=function(r,e){var t={type:"ENCRYPTED PRIVATE KEY",body:N.toDer(r).getBytes()};return ie.pem.encode(t,{maxline:e})};Pe.encryptedPrivateKeyFromPem=function(r){var e=ie.pem.decode(r)[0];if(e.type!=="ENCRYPTED PRIVATE KEY"){var t=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw t.headerType=e.type,t}if(e.procType&&e.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return N.fromDer(e.body)};Pe.encryptRsaPrivateKey=function(r,e,t){if(t=t||{},!t.legacy){var n=Pe.wrapRsaPrivateKey(Pe.privateKeyToAsn1(r));return n=Pe.encryptPrivateKeyInfo(n,e,t),Pe.encryptedPrivateKeyToPem(n)}var i,s,o,a;switch(t.algorithm){case"aes128":i="AES-128-CBC",o=16,s=ie.random.getBytesSync(16),a=ie.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",o=24,s=ie.random.getBytesSync(16),a=ie.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",o=32,s=ie.random.getBytesSync(16),a=ie.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",o=24,s=ie.random.getBytesSync(8),a=ie.des.createEncryptionCipher;break;case"des":i="DES-CBC",o=8,s=ie.random.getBytesSync(8),a=ie.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+t.algorithm+'".');throw c.algorithm=t.algorithm,c}var u=ie.pbe.opensslDeriveBytes(e,s.substr(0,8),o),l=a(u);l.start(s),l.update(N.toDer(Pe.privateKeyToAsn1(r))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:ie.util.bytesToHex(s).toUpperCase()},body:l.output.getBytes()};return ie.pem.encode(f)};Pe.decryptRsaPrivateKey=function(r,e){var t=null,n=ie.pem.decode(r)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var s,o;switch(n.dekInfo.algorithm){case"DES-CBC":s=8,o=ie.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,o=ie.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,o=ie.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,o=ie.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,o=ie.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,o=function(f){return ie.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":s=8,o=function(f){return ie.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":s=16,o=function(f){return ie.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=ie.util.hexToBytes(n.dekInfo.parameters),c=ie.pbe.opensslDeriveBytes(e,a.substr(0,8),s),u=o(c);if(u.start(a),u.update(ie.util.createBuffer(n.body)),u.finish())t=u.output.getBytes();else return t}else t=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?t=Pe.decryptPrivateKeyInfo(N.fromDer(t),e):t=N.fromDer(t),t!==null&&(t=Pe.privateKeyFromAsn1(t)),t};Pe.pbe.generatePkcs12Key=function(r,e,t,n,i,s){var o,a;if(typeof s>"u"||s===null){if(!("sha1"in ie.md))throw new Error('"sha1" hash algorithm unavailable.');s=ie.md.sha1.create()}var c=s.digestLength,u=s.blockLength,l=new ie.util.ByteBuffer,f=new ie.util.ByteBuffer;if(r!=null){for(a=0;a=0;a--)Q=Q>>8,Q+=T.at(a)+$.at(a),$.setAt(a,Q&255);q.putBuffer($)}E=q,l.putBuffer(v)}return l.truncate(l.length()-i),l};Pe.pbe.getCipher=function(r,e,t){switch(r){case Pe.oids.pkcs5PBES2:return Pe.pbe.getCipherForPBES2(r,e,t);case Pe.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case Pe.oids["pbewithSHAAnd40BitRC2-CBC"]:return Pe.pbe.getCipherForPKCS12PBE(r,e,t);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=r,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};Pe.pbe.getCipherForPBES2=function(r,e,t){var n={},i=[];if(!N.validate(e,zF,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(r=N.derToOid(n.kdfOid),r!==Pe.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=r,s.supportedOids=["pkcs5PBKDF2"],s}if(r=N.derToOid(n.encOid),r!==Pe.oids["aes128-CBC"]&&r!==Pe.oids["aes192-CBC"]&&r!==Pe.oids["aes256-CBC"]&&r!==Pe.oids["des-EDE3-CBC"]&&r!==Pe.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=r,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var o=n.kdfSalt,a=ie.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(Pe.oids[r]){case"aes128-CBC":c=16,u=ie.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=ie.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=ie.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=ie.des.createDecryptionCipher;break;case"desCBC":c=8,u=ie.des.createDecryptionCipher;break}var l=WE(n.prfOid),f=ie.pkcs5.pbkdf2(t,o,a,c,l),h=n.encIv,d=u(f);return d.start(h),d};Pe.pbe.getCipherForPKCS12PBE=function(r,e,t){var n={},i=[];if(!N.validate(e,$F,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=ie.util.createBuffer(n.salt),a=ie.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(r){case Pe.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=ie.des.startDecrypting;break;case Pe.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(m,g){var y=ie.rc2.createDecryptionCipher(m,40);return y.start(g,null),y};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=r,s}var f=WE(n.prfOid),h=Pe.pbe.generatePkcs12Key(t,o,1,a,c,f);f.start();var d=Pe.pbe.generatePkcs12Key(t,o,2,a,u,f);return l(h,d)};Pe.pbe.opensslDeriveBytes=function(r,e,t,n){if(typeof n>"u"||n===null){if(!("md5"in ie.md))throw new Error('"md5" hash algorithm unavailable.');n=ie.md.md5.create()}e===null&&(e="");for(var i=[GE(n,r+e)],s=16,o=1;s{var bt=Ve();ya();Nt();var Jl=Mx.exports=bt.sha512=bt.sha512||{};bt.md.sha512=bt.md.algorithms.sha512=Jl;var Bx=bt.sha384=bt.sha512.sha384=bt.sha512.sha384||{};Bx.create=function(){return Jl.create("SHA-384")};bt.md.sha384=bt.md.algorithms.sha384=Bx;bt.sha512.sha256=bt.sha512.sha256||{create:function(){return Jl.create("SHA-512/256")}};bt.md["sha512/256"]=bt.md.algorithms["sha512/256"]=bt.sha512.sha256;bt.sha512.sha224=bt.sha512.sha224||{create:function(){return Jl.create("SHA-512/224")}};bt.md["sha512/224"]=bt.md.algorithms["sha512/224"]=bt.sha512.sha224;Jl.create=function(r){if(Lx||oV(),typeof r>"u"&&(r="SHA-512"),!(r in Ra))throw new Error("Invalid SHA-512 algorithm: "+r);for(var e=Ra[r],t=null,n=bt.util.createBuffer(),i=new Array(80),s=0;s<80;++s)i[s]=new Array(2);var o=64;switch(r){case"SHA-384":o=48;break;case"SHA-512/256":o=32;break;case"SHA-512/224":o=28;break}var a={algorithm:r.replace("-","").toLowerCase(),blockLength:128,digestLength:o,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),Ox(t,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=bt.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(o4.substr(0,a.blockLength-l));for(var f,h,d=a.fullMessageLength[0]*8,p=0;p>>0,d+=h,c.putInt32(d>>>0),d=f>>>0;c.putInt32(d);for(var m=new Array(t.length),p=0;p=128;){for(k=0;k<16;++k)e[k][0]=t.getInt32()>>>0,e[k][1]=t.getInt32()>>>0;for(;k<80;++k)M=e[k-2],F=M[0],O=M[1],n=((F>>>19|O<<13)^(O>>>29|F<<3)^F>>>6)>>>0,i=((F<<13|O>>>19)^(O<<3|F>>>29)^(F<<26|O>>>6))>>>0,H=e[k-15],F=H[0],O=H[1],s=((F>>>1|O<<31)^(F>>>8|O<<24)^F>>>7)>>>0,o=((F<<31|O>>>1)^(F<<24|O>>>8)^(F<<25|O>>>7))>>>0,A=e[k-7],X=e[k-16],O=i+A[1]+o+X[1],e[k][0]=n+A[0]+s+X[0]+(O/4294967296>>>0)>>>0,e[k][1]=O>>>0;for(m=r[0][0],g=r[0][1],y=r[1][0],b=r[1][1],E=r[2][0],_=r[2][1],x=r[3][0],v=r[3][1],R=r[4][0],T=r[4][1],P=r[5][0],q=r[5][1],$=r[6][0],Q=r[6][1],te=r[7][0],_e=r[7][1],k=0;k<80;++k)u=((R>>>14|T<<18)^(R>>>18|T<<14)^(T>>>9|R<<23))>>>0,l=((R<<18|T>>>14)^(R<<14|T>>>18)^(T<<23|R>>>9))>>>0,f=($^R&(P^$))>>>0,h=(Q^T&(q^Q))>>>0,a=((m>>>28|g<<4)^(g>>>2|m<<30)^(g>>>7|m<<25))>>>0,c=((m<<4|g>>>28)^(g<<30|m>>>2)^(g<<25|m>>>7))>>>0,d=(m&y|E&(m^y))>>>0,p=(g&b|_&(g^b))>>>0,O=_e+l+h+a4[k][1]+e[k][1],n=te+u+f+a4[k][0]+e[k][0]+(O/4294967296>>>0)>>>0,i=O>>>0,O=c+p,s=a+d+(O/4294967296>>>0)>>>0,o=O>>>0,te=$,_e=Q,$=P,Q=q,P=R,q=T,O=v+i,R=x+n+(O/4294967296>>>0)>>>0,T=O>>>0,x=E,v=_,E=y,_=b,y=m,b=g,O=i+o,m=n+s+(O/4294967296>>>0)>>>0,g=O>>>0;O=r[0][1]+g,r[0][0]=r[0][0]+m+(O/4294967296>>>0)>>>0,r[0][1]=O>>>0,O=r[1][1]+b,r[1][0]=r[1][0]+y+(O/4294967296>>>0)>>>0,r[1][1]=O>>>0,O=r[2][1]+_,r[2][0]=r[2][0]+E+(O/4294967296>>>0)>>>0,r[2][1]=O>>>0,O=r[3][1]+v,r[3][0]=r[3][0]+x+(O/4294967296>>>0)>>>0,r[3][1]=O>>>0,O=r[4][1]+T,r[4][0]=r[4][0]+R+(O/4294967296>>>0)>>>0,r[4][1]=O>>>0,O=r[5][1]+q,r[5][0]=r[5][0]+P+(O/4294967296>>>0)>>>0,r[5][1]=O>>>0,O=r[6][1]+Q,r[6][0]=r[6][0]+$+(O/4294967296>>>0)>>>0,r[6][1]=O>>>0,O=r[7][1]+_e,r[7][0]=r[7][0]+te+(O/4294967296>>>0)>>>0,r[7][1]=O>>>0,re-=128}}});var dv=B((Mle,hv)=>{"use strict";hv.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var wv=B((yv,bv)=>{"use strict";var Ad=dv(),{hasOwnProperty:mv}=Object.prototype,{propertyIsEnumerable:FV}=Object,qc=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),KV=yv,pv={concatArrays:!1,ignoreUndefined:!1},Td=r=>{let e=[];for(let t in r)mv.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)FV.call(r,n)&&e.push(n)}return e};function zc(r){return Array.isArray(r)?VV(r):Ad(r)?qV(r):r}function VV(r){let e=r.slice(0,0);return Td(r).forEach(t=>{qc(e,t,zc(r[t]))}),e}function qV(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Td(r).forEach(t=>{qc(e,t,zc(r[t]))}),e}var gv=(r,e,t,n)=>(t.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in r&&r[i]!==Object.getPrototypeOf(r)?qc(r,i,S4(r[i],e[i],n)):qc(r,i,zc(e[i])))}),r),zV=(r,e,t)=>{let n=r.slice(0,0),i=0;return[r,e].forEach(s=>{let o=[];for(let a=0;a!o.includes(a)),t)}),n};function S4(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?zV(r,e,t):!Ad(e)||!Ad(r)?zc(e):gv(r,e,Td(e),t)}bv.exports=function(...r){let e=S4(zc(pv),this!==KV&&this||{},pv),t={_:{}};for(let n of r)if(n!==void 0){if(!Ad(n))throw new TypeError("`"+n+"` is not an Option Object");t=S4(t,{_:n},e)}return t._}});var vv=B((Fle,xv)=>{"use strict";function $V(r){return r>=55296&&r<=56319}function HV(r){return r>=56320&&r<=57343}xv.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,s=0,o,a,c=0;cn)return t.slice(0,c-a.length+1)}return t}});var Sv=B((Kle,_v)=>{"use strict";function GV(r){return r>=55296&&r<=56319}function WV(r){return r>=56320&&r<=57343}_v.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,s=null,o=0;o=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),s=i;return n}});var Iv=B((Vle,Rv)=>{"use strict";var YV=vv(),QV=Sv();Rv.exports=YV.bind(null,QV)});var Dv=B((qle,Tv)=>{"use strict";var XV=Iv(),jV=/[\/\?<>\\:\*\|"]/g,ZV=/[\x00-\x1f\x80-\x9f]/g,JV=/^\.+$/,eq=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,tq=/[\. ]+$/;function Av(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(jV,e).replace(ZV,e).replace(JV,e).replace(eq,e).replace(tq,e);return XV(t,255)}Tv.exports=function(r,e){var t=e&&e.replacement||"",n=Av(r,t);return t===""?n:Av(n,"")}});var s_=B(yf=>{(function(){var r,e,t,n,i,s,o,a;a=function(c){var u,l,f,h;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,h=c&255,[u,l,f,h].join(".")},o=function(c){var u,l,f,h,d,p;for(u=[],f=h=0;h<=3&&c.length!==0;f=++h){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],l=p[1],c=c.substring(l),u.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),i=t("A"),e=function(c){var u,l,f,h,d;for(h=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),d=f;f>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")h=h*u+(10+t(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")h=h*u+(10+t(c[f])-i)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");f++}if(f===d)throw new Error("empty octet");return[h,f]},r=function(){function c(u,l){var f,h,d,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=o(l)}catch(m){throw f=m,new Error("Invalid mask: "+l)}for(h=d=32;d>=0;h=--d)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(u)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(o(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,h;for(h=o(this.first),f=o(this.last),l=0;h<=f;)u(a(h),h,l),l++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),yf.ip2long=o,yf.long2ip=a,yf.Netmask=r}).call(yf)});var u_=B((c_,Hd)=>{(function(r){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",t={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let m=0,g=-1,y=(d.match(a.zoneIndex)||[])[0],b,E;for(y&&(y=y.substring(1),d=d.replace(/%.+$/,""));(g=d.indexOf(":",g+1))>=0;)m++;if(d.substr(0,2)==="::"&&m--,d.substr(-2,2)==="::"&&m--,m>p)return null;for(E=p-m,b=":";E--;)b+="0:";return d=d.replace("::",b),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let _=d.split(":"),x=[];for(let v=0;v<_.length;v++)x.push(parseInt(_[v],16));return x}(),{parts:p,zoneId:y}}function u(d,p,m,g){if(d.length!==p.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let y=0,b;for(;g>0;){if(b=m-g,b<0&&(b=0),d[y]>>b!==p[y]>>b)return!1;g-=m,y+=1}return!0}function l(d){if(i.test(d))return parseInt(d,16);if(d[0]==="0"&&!isNaN(parseInt(d[1],10))){if(n.test(d))return parseInt(d,8);throw new Error(`ipaddr: cannot parse ${d} as octal`)}return parseInt(d,10)}function f(d,p){for(;d.length=0;y-=1)if(b=this.octets[y],b in g){if(E=g[b],m&&E!==0)return null;E!==8&&(m=!0),p+=E}else return null;return 32-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return h.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),h.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),g=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],b=0;for(;b<4;)y.push(parseInt(m[b],10)|parseInt(g[b],10)^255),b++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.isIPv4=function(d){return this.parser(d)!==null},h.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},h.IPv4.isValidFourPartDecimal=function(d){return!!(h.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},h.IPv4.networkAddressFromCIDR=function(d){let p,m,g,y,b;try{for(p=this.parseCIDR(d),g=p[0].toByteArray(),b=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],m=0;m<4;)y.push(parseInt(g[m],10)&parseInt(b[m],10)),m++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},h.IPv4.parse=function(d){let p=this.parser(d);if(p===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(p)},h.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let m=parseInt(p[2]);if(m>=0&&m<=32){let g=[this.parse(p[1]),m];return Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},h.IPv4.parser=function(d){let p,m,g;if(p=d.match(t.fourOctet))return function(){let y=p.slice(1,6),b=[];for(let E=0;E4294967295||g<0)throw new Error("ipaddr: address outside defined range");return function(){let y=[],b;for(b=0;b<=24;b+=8)y.push(g>>b&255);return y}().reverse()}else return(p=d.match(t.twoOctet))?function(){let y=p.slice(1,4),b=[];if(g=l(y[1]),g>16777215||g<0)throw new Error("ipaddr: address outside defined range");return b.push(l(y[0])),b.push(g>>16&255),b.push(g>>8&255),b.push(g&255),b}():(p=d.match(t.threeOctet))?function(){let y=p.slice(1,5),b=[];if(g=l(y[2]),g>65535||g<0)throw new Error("ipaddr: address outside defined range");return b.push(l(y[0])),b.push(l(y[1])),b.push(g>>8&255),b.push(g&255),b}():null},h.IPv4.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>32)throw new Error("ipaddr: invalid IPv4 prefix length");let p=[0,0,0,0],m=0,g=Math.floor(d/8);for(;m=0;E-=1)if(y=this.parts[E],y in g){if(b=g[y],m&&b!==0)return null;b!==16&&(m=!0),p+=b}else return null;return 128-p},d.prototype.range=function(){return h.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,m=[],g=this.parts;for(let y=0;y>8),m.push(p&255);return m},d.prototype.toFixedLengthString=function(){let p=function(){let g=[];for(let y=0;y>8,m&255,g>>8,g&255])},d.prototype.toNormalizedString=function(){let p=function(){let g=[];for(let y=0;yy&&(g=b.index,y=b[0].length);return y<0?m:`${m.substring(0,g)}::${m.substring(g+y)}`},d.prototype.toString=function(){return this.toRFC5952String()},d}(),h.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),g=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],b=0;for(;b<16;)y.push(parseInt(m[b],10)|parseInt(g[b],10)^255),b++;return new this(y)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},h.IPv6.isIPv6=function(d){return this.parser(d)!==null},h.IPv6.isValid=function(d){if(typeof d=="string"&&d.indexOf(":")===-1)return!1;try{let p=this.parser(d);return new this(p.parts,p.zoneId),!0}catch{return!1}},h.IPv6.networkAddressFromCIDR=function(d){let p,m,g,y,b;try{for(p=this.parseCIDR(d),g=p[0].toByteArray(),b=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],m=0;m<16;)y.push(parseInt(g[m],10)&parseInt(b[m],10)),m++;return new this(y)}catch(E){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${E})`)}},h.IPv6.parse=function(d){let p=this.parser(d);if(p.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(p.parts,p.zoneId)},h.IPv6.parseCIDR=function(d){let p,m,g;if((m=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(m[2]),p>=0&&p<=128))return g=[this.parse(m[1]),p],Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},h.IPv6.parser=function(d){let p,m,g,y,b,E;if(g=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${g[1]}`);if(a.native.test(d))return c(d,8);if((g=d.match(a.transitional))&&(E=g[6]||"",p=c(g[1].slice(0,-1)+E,6),p.parts)){for(b=[parseInt(g[2]),parseInt(g[3]),parseInt(g[4]),parseInt(g[5])],m=0;m128)throw new Error("ipaddr: invalid IPv6 prefix length");let p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=0,g=Math.floor(d/8);for(;m{"use strict";g_.exports=m_;var Gq=P2(),xo=m_.prototype,Wq=new Date%1e9;function Yq(){return(Math.random()*1e9>>>0)+Wq++}function m_(r){r=r||{},this.id=r.id||Yq(),this.max=r.max||1/0,this.items=r.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(r.lastModified||new Date);for(var e,t,n=this.items.length;n--;)e=this.items[n],t=new Date(e.expires)-new Date,this._lookup[e.key]=e,t>0?this.expire(e.key,t):t<=0&&this.delete(e.key)}xo.has=function(r){return r in this._lookup};xo.get=function(r){if(!this.has(r))return null;var e=this._lookup[r];return e.refresh&&this.expire(r,e.refresh),this.items.splice(this.items.indexOf(e),1),this.items.push(e),e.value};xo.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};xo.set=function(r,e,t){var n=this._lookup[r],i=this._lookup[r]={key:r,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,i)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(i),this.size++),t&&("ttl"in t&&this.expire(r,t.ttl),"meta"in t&&(i.meta=t.meta),t.refresh&&(i.refresh=t.ttl)),this};xo.delete=function(r){var e=this._lookup[r];return e?(this.lastModified=new Date,this.items.splice(this.items.indexOf(e),1),clearTimeout(e.timeout),delete this._lookup[r],this.size--,this):!1};xo.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=Gq(e)),typeof t!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),t),n.expires=Number(new Date)+t,this};xo.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};xo.toJSON=function(){for(var r=new Array(this.items.length),e,t=r.length;t--;)e=this.items[t],r[t]={key:e.key,meta:e.meta,value:e.value,expires:e.expires,refresh:e.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:r}}});var bf=B((Hde,R_)=>{R_.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var A_=B((Wde,I_)=>{I_.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let n=Date.now();return t>=n?t-n:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var D_=B((Yde,T_)=>{var Zq=A_();T_.exports=Zq});var bn=B((Xde,C_)=>{C_.exports=class{constructor(e,t,n,i){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof i>"u"?!1:i}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var Zc=B((Zde,k_)=>{var Q4=bf(),Jq=D_(),P_=bn();k_.exports=class extends Q4{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new Jq}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,n,i,s,o={}){let a=this._getRateLimiterRes(n,i,s);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(n,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+i&&(a.msBeforeNext=this.msBlockDuration,c=this._block(n,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(n,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(u=>{t(u)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c{n(c)}).catch(c=>{i(c)}):i(e)}get _inmemoryBlockedKeys(){return this._inMemoryBlockedKeys}getInmemoryBlockMsBeforeExpire(e){return this.getInMemoryBlockMsBeforeExpire(e)}get inmemoryBlockOnConsumed(){return this.inMemoryBlockOnConsumed}set inmemoryBlockOnConsumed(e){this.inMemoryBlockOnConsumed=e}get inmemoryBlockDuration(){return this.inMemoryBlockDuration}set inmemoryBlockDuration(e){this.inMemoryBlockDuration=e}get msInmemoryBlockDuration(){return this.inMemoryBlockDuration*1e3}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof Q4))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,n={}){let i=t*1e3;return this._block(this.getKey(e),this.points+1,i,n)}set(e,t,n,i={}){let s=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),t,s,i)}consume(e,t=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return s(new P_(0,a));this._upsert(o,t,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,s,o,t,c)}).catch(c=>{this._handleError(c,"consume",i,s,e,t,n)})})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,t,a))}).catch(a=>{this._handleError(a,"penalty",s,o,e,t,n)})})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,-t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,-t,a))}).catch(a=>{this._handleError(a,"reward",s,o,e,t,n)})})}get(e,t={}){let n=this.getKey(e);return new Promise((i,s)=>{this._get(n,t).then(o=>{i(o===null||typeof o>"u"?null:this._getRateLimiterRes(n,0,o))}).catch(o=>{this._handleError(o,"get",i,s,e,t)})})}delete(e,t={}){let n=this.getKey(e);return new Promise((i,s)=>{this._delete(n,t).then(o=>{this._inMemoryBlockedKeys.delete(n),i(o)}).catch(o=>{this._handleError(o,"delete",i,s,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,n){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,n,i={}){return new Promise((s,o)=>{this._upsert(e,t,n,!0,i).then(()=>{s(new P_(0,n>0?n:-1,t))}).catch(a=>{this._handleError(a,"block",s,o,this.parseKey(e),n/1e3,i)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,n,i=!1,s={}){throw new Error("You have to implement the method '_upsert'!")}}});var B_=B((Jde,O_)=>{var ez=Zc(),tz=bn(),N_="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",X4=class extends ez{constructor(e){super(e),e.redis?this.client=e.redis:this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:N_})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,n){let[i,s]=n;Array.isArray(i)&&([,i]=i,[,s]=s);let o=new tz;return o.consumedPoints=parseInt(i),o.isFirstInDuration=o.consumedPoints===t,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=s,o}_upsert(e,t,n,i=!1){return new Promise((s,o)=>{if(!this._isRedisReady())return o(new Error("Redis connection is not ready"));let a=Math.floor(n/1e3),c=this.client.multi();if(i)a>0?c.set(e,t,"EX",a):c.set(e,t),c.pttl(e).exec((u,l)=>u?o(u):s(l));else if(a>0){let u=function(l,f){return l?o(l):s(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,a,u):this.client.eval(N_,1,e,t,a,u)}else c.incrby(e,t).pttl(e).exec((u,l)=>u?o(u):s(l))})}_get(e){return new Promise((t,n)=>{if(!this._isRedisReady())return n(new Error("Redis connection is not ready"));this.client.multi().get(e).pttl(e).exec((i,s)=>{if(i)n(i);else{let[o]=s;if(o===null)return t(null);t(s)}})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,s)=>{i?n(i):t(s>0)})})}};O_.exports=X4});var U_=B((e1e,M_)=>{var rz=Zc(),nz=bn();function L_(r){try{let e=r.client?r.client:r,{version:t}=e.topology.s.options.metadata.driver,n=t.split(".").map(i=>parseInt(i));return{major:n[0],feature:n[1],patch:n[2]}}catch{return{major:0,feature:0,patch:0}}}var j4=class r extends rz{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=L_(this.client)}):(this._initCollection(),this._driverVersion=L_(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?r.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,n){let i=new nz,s;return typeof n.value>"u"?s=n:s=n.value,i.isFirstInDuration=s.points===t,i.consumedPoints=s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire!==null?Math.max(new Date(s.expire).getTime()-Date.now(),0):-1,i}_upsert(e,t,n,i=!1,s={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=s.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:t,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let u={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?u.returnDocument="after":u.returnOriginal=!1,new Promise((l,f)=>{this._collection.findOneAndUpdate(a,c,u).then(h=>{l(h)}).catch(h=>{if(h&&h.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),p={$set:Object.assign({key:e,points:t,expire:n>0?new Date(Date.now()+n):null},o)};this._collection.findOneAndUpdate(d,p,u).then(m=>{l(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,t,n,i).then(g=>l(g)).catch(g=>f(g)):f(m)})}else f(h)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},n);return this._collection.findOne(i)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let n=t.attrs||{},i=Object.assign({key:e},n);return this._collection.deleteOne(i).then(s=>s.deletedCount>0)}};M_.exports=j4});var K_=B((t1e,F_)=>{var iz=Zc(),sz=bn(),Z4=class extends iz{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{this._getConnection().then(n=>{n.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(n),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((n,i)=>{if(n)return t(n);e(i)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(n=>{n.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,i=>{if(i)return this._releaseConnection(n),t(i);n.query(this._getCreateTableStmt(),s=>{if(s)return this._releaseConnection(n),t(s);this._releaseConnection(n),e()})})}).catch(n=>{t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,n){let i=new sz,[s]=n;return i.isFirstInDuration=t===s.points,i.consumedPoints=i.isFirstInDuration?t:s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire?Math.max(s.expire-Date.now(),0):-1,i}_upsertTransaction(e,t,n,i,s){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,f,h;s?(f=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = ?, expire = ?;`,h=[this.dbName,this.tableName,t,n,l,n,l]):(f=`INSERT INTO ??.?? VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points = IF(expire <= ?, ?, points + (?)), expire = IF(expire <= ?, ?, expire);`,h=[this.dbName,this.tableName,t,n,l,u,n,n,u,l]),e.query(f,h,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(p,m)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",g=>{if(g)return e.rollback(),a(g);o(m)})})})})})}_upsert(e,t,n,i=!1){return this.tableCreated?new Promise((s,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,n,i).then(c=>{s(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(s,o)=>{s?n(s):o.length===0?t(null):t(o),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((t,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(s,o)=>{s?n(s):t(o.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};F_.exports=Z4});var q_=B((r1e,V_)=>{var oz=Zc(),az=bn(),J4=class extends oz{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof t=="function"&&t():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(n=>{if(typeof t=="function")t(n);else throw n})}clearExpired(e){return new Promise(t=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this.tableName} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{t()}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,t)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():t(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this.tableName} ( key varchar(255) PRIMARY KEY, points integer NOT NULL DEFAULT 0, expire bigint );`}get clientType(){return this._clientType}set clientType(e){let t=this.client.constructor.name;if(typeof e>"u")if(t==="Client")e="client";else if(t==="Pool"||t==="BoundPool")e="pool";else if(t==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,n){let i=new az,s=n.rows[0];return i.isFirstInDuration=t===s.points,i.consumedPoints=i.isFirstInDuration?t:s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire?Math.max(s.expire-Date.now(),0):-1,i}_query(e){let n={name:`${this.tableName.toLowerCase()}:${e.name}`,text:e.text,values:e.values};return new Promise((i,s)=>{this._getConnection().then(o=>{o.query(n).then(a=>{i(a),this._releaseConnection(o)}).catch(a=>{s(a),this._releaseConnection(o)})}).catch(o=>{s(o)})})}_upsert(e,t,n,i=!1){if(!this.tableCreated)return Promise.reject(Error("Table is not created yet"));let s=n>0?Date.now()+n:null,o=i?" $3 ":` CASE WHEN ${this.tableName}.expire <= $4 THEN $3 ELSE ${this.tableName}.expire END `;return this._query({name:i?"rlflx-upsert-force":"rlflx-upsert",text:` INSERT INTO ${this.tableName} VALUES ($1, $2, $3) ON CONFLICT(key) DO UPDATE SET points = CASE WHEN (${this.tableName}.expire <= $4 OR 1=${i?1:0}) THEN $2 ELSE ${this.tableName}.points + ($2) END, expire = ${o} RETURNING points, expire;`,values:[e,t,s,Date.now()]})}_get(e){return this.tableCreated?new Promise((t,n)=>{this._query({name:"rlflx-get",text:` SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),t(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};V_.exports=J4});var z_=B(()=>{});var H_=B((o1e,$_)=>{$_.exports=class{constructor(e,t,n=null){this.value=e,this.expiresAt=t,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var W_=B((c1e,G_)=>{var cz=H_(),eg=bn();G_.exports=class{constructor(){this._storage={}}incrby(e,t,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+t,new eg(0,i,this._storage[e].value,!1)):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new cz(t,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new eg(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new eg(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var rg=B((u1e,Q_)=>{var uz=bf(),lz=W_(),Y_=bn(),tg=class extends uz{constructor(e={}){super(e),this._memoryStorage=new lz}consume(e,t=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(o,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,t){let n=t*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,t),Promise.resolve(new Y_(0,n===0?-1:n,i))}set(e,t,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,n),Promise.resolve(new Y_(0,i===0?-1:i,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Q_.exports=tg});var rS=B((l1e,tS)=>{var X_=z_(),fz=ba(),hz=bf(),Z_=rg(),dz=bn(),Wn="rate_limiter_flexible",tu=null,j_=function(r,e,t,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},r.send({channel:Wn,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:i})},J_=function(r){setTimeout(()=>{this._initiated?process.send(r):typeof this._promises[r.promiseId]<"u"&&J_.call(this,r)},30)},Jc=function(r,e,t,n,i){let s={channel:Wn,keyPrefix:this.keyPrefix,func:r,promiseId:e,data:{key:t,arg:n,opts:i}};this._initiated?process.send(s):J_.call(this,s)},eS=function(r,e){if(!e||e.channel!==Wn||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(n=>{j_(r,e,"resolve",n)}).catch(n=>{j_(r,e,"reject",n)})},pz=function(r){if(!r||r.channel!==Wn||r.keyPrefix!==this.keyPrefix)return!1;if(this._promises[r.promiseId]){clearTimeout(this._promises[r.promiseId].timeoutId);let e;switch(r.data===null||r.data===!0||r.data===!1?e=r.data:e=new dz(r.data.remainingPoints,r.data.msBeforeNext,r.data.consumedPoints,r.data.isFirstInDuration),r.type){case"resolve":this._promises[r.promiseId].resolve(e);break;case"reject":this._promises[r.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${r.type}'`)}delete this._promises[r.promiseId]}},mz=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},eu=function(r,e){let t=process.hrtime(),n=t[0].toString()+t[1].toString();return typeof this._promises[n]<"u"&&(n+=fz.randomBytes(12).toString("base64")),this._promises[n]={resolve:r,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},ng=class{constructor(){if(tu)return tu;this._rateLimiters={},X_.setMaxListeners(0),X_.on("message",(e,t)=>{t&&t.channel===Wn&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new Z_(t.opts)),e.send({channel:Wn,type:"init",keyPrefix:t.opts.keyPrefix})):eS.call(this,e,t)}),tu=this}},ig=class{constructor(e){if(tu)return tu;this._rateLimiters={},e.launchBus((t,n)=>{n.on("process:msg",i=>{let s=i.raw;if(s&&s.channel===Wn&&s.type==="init")typeof this._rateLimiters[s.opts.keyPrefix]>"u"&&(this._rateLimiters[s.opts.keyPrefix]=new Z_(s.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:Wn,channel:Wn,type:"init",keyPrefix:s.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=Wn,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};eS.call(this,o,s)}})}),tu=this}},sg=class extends hz{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===Wn&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:pz.call(this,t)}),process.send({channel:Wn,type:"init",opts:mz.call(this)}),this._promises={}}consume(e,t=1,n={}){return new Promise((i,s)=>{let o=eu.call(this,i,s);Jc.call(this,"consume",o,e,t,n)})}penalty(e,t=1,n={}){return new Promise((i,s)=>{let o=eu.call(this,i,s);Jc.call(this,"penalty",o,e,t,n)})}reward(e,t=1,n={}){return new Promise((i,s)=>{let o=eu.call(this,i,s);Jc.call(this,"reward",o,e,t,n)})}block(e,t,n={}){return new Promise((i,s)=>{let o=eu.call(this,i,s);Jc.call(this,"block",o,e,t,n)})}get(e,t={}){return new Promise((n,i)=>{let s=eu.call(this,n,i);Jc.call(this,"get",s,e,t)})}delete(e,t={}){return new Promise((n,i)=>{let s=eu.call(this,n,i);Jc.call(this,"delete",s,e,t)})}};tS.exports={RateLimiterClusterMaster:ng,RateLimiterClusterMasterPM2:ig,RateLimiterCluster:sg}});var iS=B((f1e,nS)=>{var gz=Zc(),yz=bn(),og=class extends gz{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,n){let i=new yz;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===t,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,t,n,i=!1,s={}){return new Promise((o,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,t,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};o(f)})}):this.client.incr(e,t,(l,f)=>{l||f===!1?this.client.add(e,t,u,(h,d)=>{if(h||!d)if(typeof s.attemptNumber>"u"||s.attemptNumber<3){let p=Object.assign({},s);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,t,n,i,p).then(m=>o(m)).catch(m=>a(m))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let p={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};o(p)})}):this.client.get(`${e}_expire`,(h,d)=>{if(h)a(h);else{let p=d===!1?0:d,m={consumedPoints:f,msBeforeNext:p>=0?Math.max(p-c,0):-1};o(m)}})})})}_get(e){return new Promise((t,n)=>{let i=Date.now();this.client.get(e,(s,o)=>{o?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:o,msBeforeNext:u>=0?Math.max(u-i,0):-1};t(l)}}):t(null)})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,s)=>{i?n(i):s===!1?t(s):this.client.del(`${e}_expire`,o=>{o?n(o):t(s)})})})}};nS.exports=og});var aS=B((d1e,oS)=>{var sS=bn();oS.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new sS(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new sS(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),n)}block(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),n)}penalty(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),n)}reward(e,t){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),n)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var uS=B((m1e,cS)=>{var bz=bf();cS.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof bz))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((n,i)=>{let s=[];this._limiters.forEach(o=>{s.push(o.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(s).then(o=>{let a={},c=!1;o.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u{lS.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var mS=B((w1e,pS)=>{var hS=fS(),dS=4294967295,ag="limiter";pS.exports=class{constructor(e,t={maxQueueSize:dS}){this._queueLimiters={KEY_DEFAULT:new Wd(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=ag){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=ag){return this._queueLimiters[t]||(this._queueLimiters[t]=new Wd(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var Wd=class{constructor(e,t={maxQueueSize:dS,key:ag}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((n,i)=>{if(e>t._limiterFlexible.points){i(new hS(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,n,i,e):t._limiterFlexible.consume(t._key,e).then(s=>{n(s.remainingPoints)}).catch(s=>{s instanceof Error?i(s):(t._queueRequest.call(t,n,i,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),s.msBeforeNext)))})})}_queueRequest(e,t,n){let i=this;i._queue.length{t.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(t.reject(n),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var yS=B((x1e,gS)=>{var cg=bn();gS.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new cg(e.remainingPoints,Math.min(e.msBeforeNext,t?t.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,t=1,n={}){return this._rateLimiter.consume(e,t,n).catch(i=>i instanceof cg?this._burstLimiter.consume(e,t,n).then(s=>Promise.resolve(this._combineRes(i,s))).catch(s=>s instanceof cg?Promise.reject(this._combineRes(i,s)):Promise.reject(s)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,n])=>this._combineRes(t,n))}get points(){return this._rateLimiter.points}}});var ug=B((v1e,bS)=>{var wz=B_(),Ez=U_(),xz=K_(),vz=q_(),{RateLimiterClusterMaster:_z,RateLimiterClusterMasterPM2:Sz,RateLimiterCluster:Rz}=rS(),Iz=rg(),Az=iS(),Tz=aS(),Dz=uS(),Cz=mS(),Pz=yS(),kz=bn();bS.exports={RateLimiterRedis:wz,RateLimiterMongo:Ez,RateLimiterMySQL:xz,RateLimiterPostgres:vz,RateLimiterMemory:Iz,RateLimiterMemcache:Az,RateLimiterClusterMaster:_z,RateLimiterClusterMasterPM2:Sz,RateLimiterCluster:Rz,RLWrapperBlackAndWhite:Tz,RateLimiterUnion:Dz,RateLimiterQueue:Cz,BurstyRateLimiter:Pz,RateLimiterRes:kz}});var BS=B((Lme,OS)=>{"use strict";OS.exports=Af;var Rg=ys();(Af.prototype=Object.create(Rg.EventEmitter.prototype)).constructor=Af;function Af(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");Rg.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}Af.prototype.rpcCall=function r(e,t,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return Rg.asPromise(r,o,e,t,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,t[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return o.emit("error",c,e),s(c);if(u===null){o.end(!0);return}if(!(u instanceof n))try{u=n[o.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return o.emit("error",l,e),s(l)}return o.emit("data",u,e),s(null,u)})}catch(a){o.emit("error",a,e),setTimeout(function(){s(a)},0);return}};Af.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var MS=B(LS=>{"use strict";var t$=LS;t$.Service=BS()});var FS=B((Ume,US)=>{"use strict";US.exports={}});var qS=B(VS=>{"use strict";var tn=VS;tn.build="minimal";tn.Writer=Zh();tn.BufferWriter=Em();tn.Reader=Xh();tn.BufferReader=dm();tn.util=ys();tn.rpc=MS();tn.roots=FS();tn.configure=KS;function KS(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}KS()});var Ig=B((Kme,zS)=>{"use strict";zS.exports=qS()});var HS=B(($S,Tf)=>{(function(r,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof b6=="function"&&typeof Tf=="object"&&Tf&&Tf.exports&&(Tf.exports=e(Ig()))})($S,function(r){"use strict";var e=r.Reader,t=r.Writer,n=r.util,i=r.roots.default||(r.roots.default={});return i.RPC=function(){function s(a){if(this.subscriptions=[],this.messages=[],a)for(var c=Object.keys(a),u=0;u>>3){case 1:f.subscriptions&&f.subscriptions.length||(f.subscriptions=[]),f.subscriptions.push(i.RPC.SubOpts.decode(c,c.uint32()));break;case 2:f.messages&&f.messages.length||(f.messages=[]),f.messages.push(i.RPC.Message.decode(c,c.uint32()));break;case 3:f.control=i.RPC.ControlMessage.decode(c,c.uint32());break;default:c.skipType(h&7);break}}return f},s.fromObject=function(c){if(c instanceof i.RPC)return c;var u=new i.RPC;if(c.subscriptions){if(!Array.isArray(c.subscriptions))throw TypeError(".RPC.subscriptions: array expected");u.subscriptions=[];for(var l=0;l>>3){case 1:d.subscribe=l.bool();break;case 2:d.topic=l.string();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.SubOpts)return l;var f=new i.RPC.SubOpts;return l.subscribe!=null&&(f.subscribe=!!l.subscribe),l.topic!=null&&(f.topic=String(l.topic)),f},a.toObject=function(l,f){f||(f={});var h={};return l.subscribe!=null&&l.hasOwnProperty("subscribe")&&(h.subscribe=l.subscribe,f.oneofs&&(h._subscribe="subscribe")),l.topic!=null&&l.hasOwnProperty("topic")&&(h.topic=l.topic,f.oneofs&&(h._topic="topic")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.Message=function(){function a(u){if(u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.from=l.bytes();break;case 2:d.data=l.bytes();break;case 3:d.seqno=l.bytes();break;case 4:d.topic=l.string();break;case 5:d.signature=l.bytes();break;case 6:d.key=l.bytes();break;default:l.skipType(p&7);break}}if(!d.hasOwnProperty("topic"))throw n.ProtocolError("missing required 'topic'",{instance:d});return d},a.fromObject=function(l){if(l instanceof i.RPC.Message)return l;var f=new i.RPC.Message;return l.from!=null&&(typeof l.from=="string"?n.base64.decode(l.from,f.from=n.newBuffer(n.base64.length(l.from)),0):l.from.length&&(f.from=l.from)),l.data!=null&&(typeof l.data=="string"?n.base64.decode(l.data,f.data=n.newBuffer(n.base64.length(l.data)),0):l.data.length&&(f.data=l.data)),l.seqno!=null&&(typeof l.seqno=="string"?n.base64.decode(l.seqno,f.seqno=n.newBuffer(n.base64.length(l.seqno)),0):l.seqno.length&&(f.seqno=l.seqno)),l.topic!=null&&(f.topic=String(l.topic)),l.signature!=null&&(typeof l.signature=="string"?n.base64.decode(l.signature,f.signature=n.newBuffer(n.base64.length(l.signature)),0):l.signature.length&&(f.signature=l.signature)),l.key!=null&&(typeof l.key=="string"?n.base64.decode(l.key,f.key=n.newBuffer(n.base64.length(l.key)),0):l.key.length&&(f.key=l.key)),f},a.toObject=function(l,f){f||(f={});var h={};return f.defaults&&(h.topic=""),l.from!=null&&l.hasOwnProperty("from")&&(h.from=f.bytes===String?n.base64.encode(l.from,0,l.from.length):f.bytes===Array?Array.prototype.slice.call(l.from):l.from,f.oneofs&&(h._from="from")),l.data!=null&&l.hasOwnProperty("data")&&(h.data=f.bytes===String?n.base64.encode(l.data,0,l.data.length):f.bytes===Array?Array.prototype.slice.call(l.data):l.data,f.oneofs&&(h._data="data")),l.seqno!=null&&l.hasOwnProperty("seqno")&&(h.seqno=f.bytes===String?n.base64.encode(l.seqno,0,l.seqno.length):f.bytes===Array?Array.prototype.slice.call(l.seqno):l.seqno,f.oneofs&&(h._seqno="seqno")),l.topic!=null&&l.hasOwnProperty("topic")&&(h.topic=l.topic),l.signature!=null&&l.hasOwnProperty("signature")&&(h.signature=f.bytes===String?n.base64.encode(l.signature,0,l.signature.length):f.bytes===Array?Array.prototype.slice.call(l.signature):l.signature,f.oneofs&&(h._signature="signature")),l.key!=null&&l.hasOwnProperty("key")&&(h.key=f.bytes===String?n.base64.encode(l.key,0,l.key.length):f.bytes===Array?Array.prototype.slice.call(l.key):l.key,f.oneofs&&(h._key="key")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlMessage=function(){function a(c){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],c)for(var u=Object.keys(c),l=0;l>>3){case 1:h.ihave&&h.ihave.length||(h.ihave=[]),h.ihave.push(i.RPC.ControlIHave.decode(u,u.uint32()));break;case 2:h.iwant&&h.iwant.length||(h.iwant=[]),h.iwant.push(i.RPC.ControlIWant.decode(u,u.uint32()));break;case 3:h.graft&&h.graft.length||(h.graft=[]),h.graft.push(i.RPC.ControlGraft.decode(u,u.uint32()));break;case 4:h.prune&&h.prune.length||(h.prune=[]),h.prune.push(i.RPC.ControlPrune.decode(u,u.uint32()));break;default:u.skipType(d&7);break}}return h},a.fromObject=function(u){if(u instanceof i.RPC.ControlMessage)return u;var l=new i.RPC.ControlMessage;if(u.ihave){if(!Array.isArray(u.ihave))throw TypeError(".RPC.ControlMessage.ihave: array expected");l.ihave=[];for(var f=0;f>>3){case 1:d.topicID=l.string();break;case 2:d.messageIDs&&d.messageIDs.length||(d.messageIDs=[]),d.messageIDs.push(l.bytes());break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlIHave)return l;var f=new i.RPC.ControlIHave;if(l.topicID!=null&&(f.topicID=String(l.topicID)),l.messageIDs){if(!Array.isArray(l.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");f.messageIDs=[];for(var h=0;h>>3){case 1:h.messageIDs&&h.messageIDs.length||(h.messageIDs=[]),h.messageIDs.push(u.bytes());break;default:u.skipType(d&7);break}}return h},a.fromObject=function(u){if(u instanceof i.RPC.ControlIWant)return u;var l=new i.RPC.ControlIWant;if(u.messageIDs){if(!Array.isArray(u.messageIDs))throw TypeError(".RPC.ControlIWant.messageIDs: array expected");l.messageIDs=[];for(var f=0;f>>3){case 1:d.topicID=l.string();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlGraft)return l;var f=new i.RPC.ControlGraft;return l.topicID!=null&&(f.topicID=String(l.topicID)),f},a.toObject=function(l,f){f||(f={});var h={};return l.topicID!=null&&l.hasOwnProperty("topicID")&&(h.topicID=l.topicID,f.oneofs&&(h._topicID="topicID")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlPrune=function(){function a(u){if(this.peers=[],u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.topicID=l.string();break;case 2:d.peers&&d.peers.length||(d.peers=[]),d.peers.push(i.RPC.PeerInfo.decode(l,l.uint32()));break;case 3:d.backoff=l.uint64();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.ControlPrune)return l;var f=new i.RPC.ControlPrune;if(l.topicID!=null&&(f.topicID=String(l.topicID)),l.peers){if(!Array.isArray(l.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");f.peers=[];for(var h=0;h>>0,l.backoff.high>>>0).toNumber(!0))),f},a.toObject=function(l,f){f||(f={});var h={};if((f.arrays||f.defaults)&&(h.peers=[]),l.topicID!=null&&l.hasOwnProperty("topicID")&&(h.topicID=l.topicID,f.oneofs&&(h._topicID="topicID")),l.peers&&l.peers.length){h.peers=[];for(var d=0;d>>0,l.backoff.high>>>0).toNumber(!0):l.backoff,f.oneofs&&(h._backoff="backoff")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.PeerInfo=function(){function a(u){if(u)for(var l=Object.keys(u),f=0;f>>3){case 1:d.peerID=l.bytes();break;case 2:d.signedPeerRecord=l.bytes();break;default:l.skipType(p&7);break}}return d},a.fromObject=function(l){if(l instanceof i.RPC.PeerInfo)return l;var f=new i.RPC.PeerInfo;return l.peerID!=null&&(typeof l.peerID=="string"?n.base64.decode(l.peerID,f.peerID=n.newBuffer(n.base64.length(l.peerID)),0):l.peerID.length&&(f.peerID=l.peerID)),l.signedPeerRecord!=null&&(typeof l.signedPeerRecord=="string"?n.base64.decode(l.signedPeerRecord,f.signedPeerRecord=n.newBuffer(n.base64.length(l.signedPeerRecord)),0):l.signedPeerRecord.length&&(f.signedPeerRecord=l.signedPeerRecord)),f},a.toObject=function(l,f){f||(f={});var h={};return l.peerID!=null&&l.hasOwnProperty("peerID")&&(h.peerID=f.bytes===String?n.base64.encode(l.peerID,0,l.peerID.length):f.bytes===Array?Array.prototype.slice.call(l.peerID):l.peerID,f.oneofs&&(h._peerID="peerID")),l.signedPeerRecord!=null&&l.hasOwnProperty("signedPeerRecord")&&(h.signedPeerRecord=f.bytes===String?n.base64.encode(l.signedPeerRecord,0,l.signedPeerRecord.length):f.bytes===Array?Array.prototype.slice.call(l.signedPeerRecord):l.signedPeerRecord,f.oneofs&&(h._signedPeerRecord="signedPeerRecord")),h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s}(),i})});var rR=B((h3e,tR)=>{"use strict";function At(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}At.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};At.prototype.get=function(e){return this.peekAt(e)};At.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};At.prototype.peekFront=function(){return this.peek()};At.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(At.prototype,"length",{get:function(){return this.size()}});At.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};At.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}};At.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var s=this._list[t],o;if(e0;o--)this._list[t]=this._list[t=t-1+i&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+i&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+i&this._capacityMask}return s}}};At.prototype.remove=function(e,t){var n=e,i,s=t;if(n===(n|0)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(n>=o||n<-o||t<1)){if(n<0&&(n+=o),t===1||!t)return i=new Array(1),i[0]=this.removeOne(n),i;if(n===0&&n+t>=o)return i=this.toArray(),this.clear(),i;n+t>o&&(t=o-n);var c;for(i=new Array(t),c=0;c0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return i}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return i}if(n0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;s>0;)this._list[n=n-1+a&this._capacityMask]=void 0,s--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=o-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;s>0;)this._list[n=n+1+a&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),i}}};At.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var i=this.size();if(n<0&&(n+=i),!(n>i))if(arguments.length>2){var s,o,a,c=arguments.length,u=this._list.length,l=2;if(!i||n0&&(this._head=this._head+n+u&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+u&this._capacityMask);c>l;)this.unshift(arguments[--c]);for(s=n;s>0;s--)this.unshift(o[s-1])}else{o=new Array(i-(n+t));var f=o.length;for(s=0;sthis._tail){for(c=this._head;c>>=1,this._capacityMask>>>=1};At.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),n=1<{xI.exports=r=>async function*(){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let i of r){typeof i=="string"&&(i=new TextEncoder().encode(i)),n+=t.decode(i,{stream:!0});let s=n.split(e);n=s.pop();for(let o=0;o{vI.exports=r=>async function*(){for await(let e of r)yield JSON.stringify(e)+` `}()});var SI=B((R8e,F1)=>{F1.exports=uy();F1.exports.parse=uy();F1.exports.stringify=_I()});var GI=B((a6e,HI)=>{HI.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function i(s,o){t[s]=o,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var o=t[s];if(o!==void 0)return o;if((o=n[s])!==void 0)return i(s,o),o},set:function(s,o){t[s]!==void 0?t[s]=o:i(s,o)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var FA=B((Ewe,UA)=>{"use strict";function $G(r){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t>>0,E=new Uint8Array(b);g!==y;){for(var _=d[g],x=0,v=b-1;(_!==0||x>>0,E[v]=_%o>>>0,_=_/o>>>0;if(_!==0)throw new Error("Non-zero carry");m=x,g++}for(var R=b-m;R!==b&&E[R]===0;)R++;for(var T=a.repeat(p);R>>0,b=new Uint8Array(y);d[p];){var E=e[d.charCodeAt(p)];if(E===255)return;for(var _=0,x=y-1;(E!==0||_>>0,b[x]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=_,p++}if(d[p]!==" "){for(var v=y-g;v!==y&&b[v]===0;)v++;for(var R=new Uint8Array(m+(y-v)),T=m;v!==y;)R[T++]=b[v++];return R}}}function h(d){var p=f(d);if(p)return p;throw new Error("Non-base"+o+" character")}return{encode:l,decodeUnsafe:f,decode:h}}UA.exports=$G});var vp=B((xwe,KA)=>{"use strict";var HG=new TextDecoder,GG=r=>HG.decode(r),WG=new TextEncoder,YG=r=>WG.encode(r);function QG(r,e){let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}KA.exports={decodeText:GG,encodeText:YG,concat:QG}});var qA=B((vwe,VA)=>{"use strict";var{encodeText:XG}=vp(),Gy=class{constructor(e,t,n,i){this.name=e,this.code=t,this.codeBuf=XG(this.code),this.alphabet=i,this.codec=n(i)}encode(e){return this.codec.encode(e)}decode(e){for(let t of e)if(this.alphabet&&this.alphabet.indexOf(t)<0)throw new Error(`invalid character '${t}' in '${e}'`);return this.codec.decode(e)}};VA.exports=Gy});var $A=B((_we,zA)=>{"use strict";var jG=(r,e,t)=>{let n={};for(let u=0;u=8&&(o-=8,s[c++]=255&a>>o)}if(o>=t||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return s},ZG=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<e=>({encode(t){return ZG(t,e,r)},decode(t){return jG(t,e,r)}});zA.exports={rfc4648:JG}});var YA=B((Swe,WA)=>{"use strict";var Qf=FA(),eW=qA(),{rfc4648:Sr}=$A(),{decodeText:tW,encodeText:rW}=vp(),nW=()=>({encode:tW,decode:rW}),HA=[["identity","\0",nW,""],["base2","0",Sr(1),"01"],["base8","7",Sr(3),"01234567"],["base10","9",Qf,"0123456789"],["base16","f",Sr(4),"0123456789abcdef"],["base16upper","F",Sr(4),"0123456789ABCDEF"],["base32hex","v",Sr(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",Sr(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",Sr(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",Sr(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",Sr(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",Sr(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",Sr(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",Sr(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",Sr(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",Qf,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",Qf,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",Qf,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",Qf,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",Sr(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",Sr(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",Sr(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",Sr(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],GA=HA.reduce((r,e)=>(r[e[0]]=new eW(e[0],e[1],e[2],e[3]),r),{}),iW=HA.reduce((r,e)=>(r[e[1]]=GA[e[0]],r),{});WA.exports={names:GA,codes:iW}});var jA=B((Fs,XA)=>{"use strict";var Tu=YA(),{encodeText:sW,decodeText:_p,concat:QA}=vp();function oW(r,e){if(!e)throw new Error("requires an encoded Uint8Array");let{name:t,codeBuf:n}=Ya(r);return lW(t,e),QA([n,e],n.length+e.length)}function aW(r,e){let t=Ya(r),n=sW(t.encode(e));return QA([t.codeBuf,n],t.codeBuf.length+n.length)}function cW(r){r instanceof Uint8Array&&(r=_p(r));let e=r[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(e)&&(r=r.toLowerCase()),Ya(r[0]).decode(r.substring(1))}function uW(r){if(r instanceof Uint8Array&&(r=_p(r)),Object.prototype.toString.call(r)!=="[object String]")return!1;try{return Ya(r[0]).name}catch{return!1}}function lW(r,e){Ya(r).decode(_p(e))}function Ya(r){if(Object.prototype.hasOwnProperty.call(Tu.names,r))return Tu.names[r];if(Object.prototype.hasOwnProperty.call(Tu.codes,r))return Tu.codes[r];throw new Error(`Unsupported encoding: ${r}`)}function fW(r){return r instanceof Uint8Array&&(r=_p(r)),Ya(r[0])}Fs=XA.exports=oW;Fs.encode=aW;Fs.decode=cW;Fs.isEncoded=uW;Fs.encoding=Ya;Fs.encodingFromData=fW;var hW=Object.freeze(Tu.names),dW=Object.freeze(Tu.codes);Fs.names=hW;Fs.codes=dW});var tT=B((Rwe,eT)=>{eT.exports=JA;var ZA=128,pW=127,mW=~pW,gW=Math.pow(2,31);function JA(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gW;)e[t++]=r&255|ZA,r/=128;for(;r&mW;)e[t++]=r&255|ZA,r>>>=7;return e[t]=r|0,JA.bytes=t-n+1,e}});var iT=B((Iwe,nT)=>{nT.exports=Wy;var yW=128,rT=127;function Wy(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw Wy.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&rT)<=yW);return Wy.bytes=s-n,t}});var oT=B((Awe,sT)=>{var bW=Math.pow(2,7),wW=Math.pow(2,14),EW=Math.pow(2,21),xW=Math.pow(2,28),vW=Math.pow(2,35),_W=Math.pow(2,42),SW=Math.pow(2,49),RW=Math.pow(2,56),IW=Math.pow(2,63);sT.exports=function(r){return r{aT.exports={encode:tT(),decode:iT(),encodingLength:oT()}});var lT=B((Dwe,uT)=>{"use strict";var AW=Object.freeze({identity:0,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,"murmur3-128":34,"murmur3-32":35,"dbl-sha2-256":86,md4:212,md5:213,bmt:214,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082});uT.exports={names:AW}});function TW(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,_=new Uint8Array(E);y!==b;){for(var x=p[y],v=0,R=E-1;(x!==0||v>>0,_[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=v,y++}for(var T=E-g;T!==E&&_[T]===0;)T++;for(var P=c.repeat(m);T>>0,E=new Uint8Array(b);p[m];){var _=t[p.charCodeAt(m)];if(_===255)return;for(var x=0,v=b-1;(_!==0||x>>0,E[v]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=x,m++}if(p[m]!==" "){for(var R=b-y;R!==b&&E[R]===0;)R++;for(var T=new Uint8Array(g+(b-R)),P=g;R!==b;)T[P++]=E[R++];return T}}}function d(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var DW,CW,fT,hT=et(()=>{DW=TW,CW=DW,fT=CW});var Pwe,dT,Ks,pT,mT,No=et(()=>{Pwe=new Uint8Array(0),dT=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},pT=r=>new TextEncoder().encode(r),mT=r=>new TextDecoder().decode(r)});var Yy,Qy,Xy,yT,jy,Du,Oo,PW,kW,Lt,Di=et(()=>{hT();No();Yy=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Qy=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return yT(this,e)}},Xy=class{constructor(e){this.decoders=e}or(e){return yT(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},yT=(r,e)=>new Xy({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),jy=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Yy(e,t,n),this.decoder=new Qy(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Du=({name:r,prefix:e,encode:t,decode:n})=>new jy(r,e,t,n),Oo=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=fT(t,e);return Du({prefix:r,name:e,encode:n,decode:s=>Ks(i(s))})},PW=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},kW=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<Du({prefix:e,name:r,encode(i){return kW(i,n,t)},decode(i){return PW(i,n,t,r)}})});var Zy={};be(Zy,{identity:()=>NW});var NW,bT=et(()=>{Di();No();NW=Du({prefix:"\0",name:"identity",encode:r=>mT(r),decode:r=>pT(r)})});var Jy={};be(Jy,{base2:()=>OW});var OW,wT=et(()=>{Di();OW=Lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var e8={};be(e8,{base8:()=>BW});var BW,ET=et(()=>{Di();BW=Lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var t8={};be(t8,{base10:()=>LW});var LW,xT=et(()=>{Di();LW=Oo({prefix:"9",name:"base10",alphabet:"0123456789"})});var r8={};be(r8,{base16:()=>MW,base16upper:()=>UW});var MW,UW,vT=et(()=>{Di();MW=Lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UW=Lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var n8={};be(n8,{base32:()=>Cu,base32hex:()=>qW,base32hexpad:()=>$W,base32hexpadupper:()=>HW,base32hexupper:()=>zW,base32pad:()=>KW,base32padupper:()=>VW,base32upper:()=>FW,base32z:()=>GW});var Cu,FW,KW,VW,qW,zW,$W,HW,GW,i8=et(()=>{Di();Cu=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),FW=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),KW=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),VW=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qW=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zW=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$W=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),HW=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),GW=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var s8={};be(s8,{base36:()=>WW,base36upper:()=>YW});var WW,YW,_T=et(()=>{Di();WW=Oo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),YW=Oo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var o8={};be(o8,{base58btc:()=>rs,base58flickr:()=>QW});var rs,QW,a8=et(()=>{Di();rs=Oo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),QW=Oo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var c8={};be(c8,{base64:()=>XW,base64pad:()=>jW,base64url:()=>ZW,base64urlpad:()=>JW});var XW,jW,ZW,JW,ST=et(()=>{Di();XW=Lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jW=Lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ZW=Lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JW=Lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var u8={};be(u8,{base256emoji:()=>iY});function rY(r){return r.reduce((e,t)=>(e+=eY[t],e),"")}function nY(r){let e=[];for(let t of r){let n=tY[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var RT,eY,tY,iY,IT=et(()=>{Di();RT=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),eY=RT.reduce((r,e,t)=>(r[t]=e,r),[]),tY=RT.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);iY=Du({prefix:"\u{1F680}",name:"base256emoji",encode:rY,decode:nY})});function DT(r,e,t){e=e||[],t=t||0;for(var n=t;r>=cY;)e[t++]=r&255|AT,r/=128;for(;r&aY;)e[t++]=r&255|AT,r>>>=7;return e[t]=r|0,DT.bytes=t-n+1,e}function l8(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw l8.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&TT)<=lY);return l8.bytes=s-n,t}var sY,AT,oY,aY,cY,uY,lY,TT,fY,hY,dY,pY,mY,gY,yY,bY,wY,EY,xY,vY,Xf,CT=et(()=>{sY=DT,AT=128,oY=127,aY=~oY,cY=Math.pow(2,31);uY=l8,lY=128,TT=127;fY=Math.pow(2,7),hY=Math.pow(2,14),dY=Math.pow(2,21),pY=Math.pow(2,28),mY=Math.pow(2,35),gY=Math.pow(2,42),yY=Math.pow(2,49),bY=Math.pow(2,56),wY=Math.pow(2,63),EY=function(r){return r{CT();jf=(r,e=0)=>[Xf.decode(r,e),Xf.decode.bytes],Pu=(r,e,t=0)=>(Xf.encode(r,e,t),e),ku=r=>Xf.encodingLength(r)});var Qa,PT,kT,Nu,Jf=et(()=>{No();Rp();Qa=(r,e)=>{let t=e.byteLength,n=ku(r),i=n+ku(t),s=new Uint8Array(i+t);return Pu(r,s,0),Pu(t,s,n),s.set(e,i),new Nu(r,t,e,s)},PT=r=>{let e=Ks(r),[t,n]=jf(e),[i,s]=jf(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Nu(t,i,o,e)},kT=(r,e)=>r===e?!0:r.code===e.code&&r.size===e.size&&dT(r.bytes,e.bytes),Nu=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}}});var h8,f8,d8=et(()=>{Jf();h8=({name:r,code:e,encode:t})=>new f8(r,e,t),f8=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Qa(this.code,t):t.then(n=>Qa(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var p8={};be(p8,{sha256:()=>_Y,sha512:()=>SY});var OT,_Y,SY,BT=et(()=>{d8();OT=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),_Y=h8({name:"sha2-256",code:18,encode:OT("SHA-256")}),SY=h8({name:"sha2-512",code:19,encode:OT("SHA-512")})});var m8={};be(m8,{identity:()=>AY});var LT,RY,MT,IY,AY,UT=et(()=>{No();Jf();LT=0,RY="identity",MT=Ks,IY=r=>Qa(LT,MT(r)),AY={code:LT,name:RY,encode:MT,digest:IY}});var FT=et(()=>{No()});var Zwe,Jwe,KT=et(()=>{Zwe=new TextEncoder,Jwe=new TextDecoder});var Tp,CY,PY,kY,eh,NY,VT,qT,Ip,Ap,OY,BY,LY,zT=et(()=>{Rp();Jf();a8();i8();No();Tp=class r{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Ap,byteLength:Ap,code:Ip,version:Ip,multihash:Ip,bytes:Ip,_baseCache:Ap,asCID:Ap})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:t}=this;if(e!==eh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==NY)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Qa(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&kT(this.multihash,e.multihash)}toString(e){let{bytes:t,version:n,_baseCache:i}=this;switch(n){case 0:return PY(t,i,e||rs.encoder);default:return kY(t,i,e||Cu.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return BY(/^0\.0/,LY),!!(e&&(e[qT]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof r)return e;if(e!=null&&e.asCID===e){let{version:t,code:n,multihash:i,bytes:s}=e;return new r(t,n,i,s||VT(t,n,i.bytes))}else if(e!=null&&e[qT]===!0){let{version:t,multihash:n,code:i}=e,s=PT(n);return r.create(t,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(t!==eh)throw new Error(`Version 0 CID must use dag-pb (code: ${eh}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=VT(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,eh,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=Ks(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new Nu(t.multihashCode,t.digestSize,s,i);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=jf(e.subarray(t));return t+=h,f},i=n(),s=eh;if(i===18?(i=0,t=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),u=t+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=CY(e,t),s=r.decode(i);return s._baseCache.set(n,e),s}},CY=(r,e)=>{switch(r[0]){case"Q":{let t=e||rs;return[rs.prefix,t.decode(`${rs.prefix}${r}`)]}case rs.prefix:{let t=e||rs;return[rs.prefix,t.decode(r)]}case Cu.prefix:{let t=e||Cu;return[Cu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},PY=(r,e,t)=>{let{prefix:n}=t;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},kY=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},eh=112,NY=18,VT=(r,e,t)=>{let n=ku(r),i=n+ku(e),s=new Uint8Array(i+t.byteLength);return Pu(r,s,0),Pu(e,s,n),s.set(t,i),s},qT=Symbol.for("@ipld/js-cid/CID"),Ip={writable:!1,configurable:!1,enumerable:!0},Ap={writable:!1,enumerable:!1,configurable:!1},OY="0.0.0-dev",BY=(r,e)=>{if(r.test(OY))console.warn(e);else throw new Error(e)},LY=`CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: if (CID.isCID(value)) { doSomethingWithCID(value) } Is replaced with: const cid = CID.asCID(value) if (cid) { // Make sure to use cid instead of value doSomethingWithCID(cid) } `});var $T=et(()=>{zT();Rp();No();d8();Jf()});var g8,aEe,HT=et(()=>{bT();wT();ET();xT();vT();i8();_T();a8();ST();IT();BT();UT();FT();KT();$T();g8={...Zy,...Jy,...e8,...t8,...r8,...n8,...s8,...o8,...c8,...u8},aEe={...p8,...m8}});function Ou(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var Dp=et(()=>{});function Cp(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ou(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var y8=et(()=>{Dp()});function WT(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var GT,b8,MY,Pp,w8=et(()=>{HT();y8();GT=WT("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),b8=WT("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=Cp(r.length);for(let t=0;tUY});function UY(r,e="utf8"){let t=Pp[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var QT=et(()=>{w8()});var XT={};be(XT,{fromString:()=>FY});function FY(r,e="utf8"){let t=Pp[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ou(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var jT=et(()=>{w8();Dp()});var ZT={};be(ZT,{concat:()=>KY});function KY(r,e){e||(e=r.reduce((i,s)=>i+s.length,0));let t=Cp(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return Ou(t)}var JT=et(()=>{y8();Dp()});var x8=B((EEe,sD)=>{"use strict";var eD=jA(),Bu=cT(),{names:th}=lT(),{toString:kp}=(QT(),Bh(YT)),{fromString:VY}=(jT(),Bh(XT)),{concat:qY}=(JT(),Bh(ZT)),Lu={};for(let r in th){let e=r;Lu[th[e]]=e}Object.freeze(Lu);function zY(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return kp(r,"base16")}function $Y(r){return VY(r,"base16")}function HY(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return kp(eD.encode("base58btc",r)).slice(1)}function GY(r){let e=r instanceof Uint8Array?kp(r):r;return eD.decode("z"+e)}function tD(r){if(!(r instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(r.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=Bu.decode(r);if(!nD(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);r=r.slice(Bu.decode.bytes);let t=Bu.decode(r);if(t<0)throw new Error(`multihash invalid length: ${t}`);if(r=r.slice(Bu.decode.bytes),r.length!==t)throw new Error(`multihash length inconsistent: 0x${kp(r,"base16")}`);return{code:e,name:Lu[e],length:t,digest:r}}function WY(r,e,t){if(!r||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=rD(e);if(!(r instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(t==null&&(t=r.length),t&&r.length!==t)throw new Error("digest length should be equal to specified length.");let i=Bu.encode(n),s=Bu.encode(t);return qY([i,s,r],i.length+s.length+r.length)}function rD(r){let e=r;if(typeof r=="string"){if(th[r]===void 0)throw new Error(`Unrecognized hash function named: ${r}`);e=th[r]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(Lu[e]===void 0&&!E8(e))throw new Error(`Unrecognized function code: ${e}`);return e}function E8(r){return r>0&&r<16}function nD(r){return!!(E8(r)||Lu[r])}function iD(r){tD(r)}function YY(r){return iD(r),r.subarray(0,2)}sD.exports={names:th,codes:Lu,toHexString:zY,fromHexString:$Y,toB58String:HY,fromB58String:GY,decode:tD,encode:WY,coerceCode:rD,isAppCode:E8,validate:iD,prefix:YY,isValidCode:nD}});var xD=B(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var A8=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&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(let 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(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&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((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},Lp=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new A8;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:s=>i.push(s),stop:()=>i.stop(),fail:s=>i.fail(s),on:(s,o)=>{i.eventHandlers[s]=o}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};Mp.EventIterator=Lp;Mp.default=Lp});var vD=B(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var T8=xD();rh.EventIterator=T8.EventIterator;function iQ(r,e,t){return new T8.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}rh.subscribe=iQ;rh.default=T8.EventIterator});var C8=B((rxe,DD)=>{"use strict";var sQ=typeof navigator<"u"&&navigator.product==="ReactNative";function oQ(){return sQ?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}var nh=self.URL,TD=oQ(),D8=class{constructor(e="",t=TD){this.super=new nh(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return nh.createObjectURL(e)}static revokeObjectURL(e){nh.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}};function aQ(r){if(typeof r=="string")return new nh(r).toString();if(!(r instanceof nh)){let e=r.username&&r.password?`${r.username}:${r.password}@`:"",t=r.auth?r.auth+"@":"",n=r.port?":"+r.port:"",i=r.protocol?r.protocol+"//":"",s=r.host||"",o=r.hostname||"",a=r.search||(r.query?"?"+r.query:""),c=r.hash||"",u=r.pathname||"",l=r.path||u+a;return`${i}${e||t}${s||o+n}${l}${c}`}}DD.exports={URLWithLegacySupport:D8,URLSearchParams:self.URLSearchParams,defaultBase:TD,format:aQ}});var kD=B((nxe,PD)=>{"use strict";var{URLWithLegacySupport:CD,format:cQ}=C8();PD.exports=(r,e={},t={},n)=>{let i=e.protocol?e.protocol.replace(":",""):"http";i=(t[i]||n||i)+":";let s;try{s=new CD(r)}catch{s={}}let o=Object.assign({},e,{protocol:i||s.protocol,host:e.host||s.host});return new CD(r,cQ(o)).toString()}});var OD=B((ixe,ND)=>{"use strict";var{URLWithLegacySupport:uQ,format:lQ,URLSearchParams:fQ,defaultBase:hQ}=C8(),dQ=kD();ND.exports={URL:uQ,URLSearchParams:fQ,format:lQ,relative:dQ,defaultBase:hQ}});var FD=B((lxe,UD)=>{function gQ(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}UD.exports=gQ});var Kk=B((wIe,Fk)=>{function ni(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.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))}Fk.exports=ni;ni.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};ni.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};ni.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!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)},t),this._options.unref&&this._timer.unref(),!0};ni.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};ni.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};ni.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};ni.prototype.start=ni.prototype.try;ni.prototype.errors=function(){return this._errors};ni.prototype.attempts=function(){return this._attempts};ni.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n=t&&(e=i,t=o)}return e}});var Vk=B(rc=>{var gZ=Kk();rc.operation=function(r){var e=rc.timeouts(r);return new gZ(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};rc.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i{qk.exports=Vk()});var LZ={};be(LZ,{createHelia:()=>OZ});var sn=j(Uh(),1);var L2={};be(L2,{base32:()=>Zt,base32hex:()=>eO,base32hexpad:()=>rO,base32hexpadupper:()=>nO,base32hexupper:()=>tO,base32pad:()=>ZN,base32padupper:()=>JN,base32upper:()=>jN,base32z:()=>iO});function GN(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,_=new Uint8Array(E);y!==b;){for(var x=p[y],v=0,R=E-1;(x!==0||v>>0,_[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=v,y++}for(var T=E-g;T!==E&&_[T]===0;)T++;for(var P=c.repeat(m);T>>0,E=new Uint8Array(b);p[m];){var _=t[p.charCodeAt(m)];if(_===255)return;for(var x=0,v=b-1;(_!==0||x>>0,E[v]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=x,m++}if(p[m]!==" "){for(var R=b-y;R!==b&&E[R]===0;)R++;for(var T=new Uint8Array(g+(b-R)),P=g;R!==b;)T[P++]=E[R++];return T}}}function d(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var WN=GN,YN=WN,_6=YN;var VZ=new Uint8Array(0);var S6=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var R6=r=>new TextEncoder().encode(r),I6=r=>new TextDecoder().decode(r);var k2=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},N2=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return T6(this,e)}},O2=class{constructor(e){this.decoders=e}or(e){return T6(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},T6=(r,e)=>new O2({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),B2=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new k2(e,t,n),this.decoder=new N2(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},oc=({name:r,prefix:e,encode:t,decode:n})=>new B2(r,e,t,n),Ws=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=_6(t,e);return oc({prefix:r,name:e,encode:n,decode:s=>ls(i(s))})},QN=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},XN=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<oc({prefix:e,name:r,encode(i){return XN(i,n,t)},decode(i){return QN(i,n,t,r)}});var Zt=Ct({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jN=Ct({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ZN=Ct({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),JN=Ct({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),eO=Ct({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tO=Ct({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rO=Ct({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nO=Ct({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),iO=Ct({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var M2={};be(M2,{base58btc:()=>Re,base58flickr:()=>sO});var Re=Ws({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sO=Ws({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var F2={};be(F2,{base64:()=>fs,base64pad:()=>oO,base64url:()=>U2,base64urlpad:()=>aO});var fs=Ct({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),oO=Ct({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),U2=Ct({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aO=Ct({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});sn.default.formatters.b=r=>r==null?"undefined":Re.baseEncode(r);sn.default.formatters.t=r=>r==null?"undefined":Zt.baseEncode(r);sn.default.formatters.m=r=>r==null?"undefined":fs.baseEncode(r);sn.default.formatters.p=r=>r==null?"undefined":r.toString();sn.default.formatters.c=r=>r==null?"undefined":r.toString();sn.default.formatters.k=r=>r==null?"undefined":r.toString();sn.default.formatters.a=r=>r==null?"undefined":r.toString();function cO(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function C(r){let e=cO(`${r}:trace`);return sn.default.enabled(`${r}:trace`)&&sn.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,sn.default)(`${r}:trace`)),Object.assign((0,sn.default)(r),{error:(0,sn.default)(`${r}:error`),trace:e})}var cc={};be(cc,{abortedError:()=>pO,closeFailedError:()=>fO,deleteFailedError:()=>k6,getFailedError:()=>hO,hasFailedError:()=>dO,notFoundError:()=>fl,openFailedError:()=>lO,putFailedError:()=>P6});var hs=j(ac(),1);function lO(r){return r=r??new Error("Open failed"),(0,hs.default)(r,"ERR_OPEN_FAILED")}function fO(r){return r=r??new Error("Close failed"),(0,hs.default)(r,"ERR_CLOSE_FAILED")}function P6(r){return r=r??new Error("Put failed"),(0,hs.default)(r,"ERR_PUT_FAILED")}function hO(r){return r=r??new Error("Get failed"),(0,hs.default)(r,"ERR_GET_FAILED")}function k6(r){return r=r??new Error("Delete failed"),(0,hs.default)(r,"ERR_DELETE_FAILED")}function dO(r){return r=r??new Error("Has failed"),(0,hs.default)(r,"ERR_HAS_FAILED")}function fl(r){return r=r??new Error("Not Found"),(0,hs.default)(r,"ERR_NOT_FOUND")}function pO(r){return r=r??new Error("Aborted"),(0,hs.default)(r,"ERR_ABORTED")}var ta=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var mO=B6,N6=128,gO=127,yO=~gO,bO=Math.pow(2,31);function B6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=bO;)e[t++]=r&255|N6,r/=128;for(;r&yO;)e[t++]=r&255|N6,r>>>=7;return e[t]=r|0,B6.bytes=t-n+1,e}var wO=K2,EO=128,O6=127;function K2(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw K2.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&O6)<=EO);return K2.bytes=s-n,t}var xO=Math.pow(2,7),vO=Math.pow(2,14),_O=Math.pow(2,21),SO=Math.pow(2,28),RO=Math.pow(2,35),IO=Math.pow(2,42),AO=Math.pow(2,49),TO=Math.pow(2,56),DO=Math.pow(2,63),CO=function(r){return r[hl.decode(r,e),hl.decode.bytes],uc=(r,e,t=0)=>(hl.encode(r,e,t),e),lc=r=>hl.encodingLength(r);var si={};be(si,{Digest:()=>ra,create:()=>ii,decode:()=>Ui,equals:()=>V2});var ii=(r,e)=>{let t=e.byteLength,n=lc(r),i=n+lc(t),s=new Uint8Array(i+t);return uc(r,s,0),uc(t,s,n),s.set(e,i),new ra(r,t,e,s)},Ui=r=>{let e=ls(r),[t,n]=dl(e),[i,s]=dl(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new ra(t,i,o,e)},V2=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&S6(r.bytes,t.bytes)}},ra=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var L6=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return OO(t,q2(r),e||Re.encoder);default:return BO(t,q2(r),e||Zt.encoder)}};var M6=new WeakMap,q2=r=>{let e=M6.get(r);if(e==null){let t=new Map;return M6.set(r,t),t}return e},Ne=class r{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==pl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==LO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ii(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&V2(e.multihash,n.multihash)}toString(e){return L6(this,e)}toJSON(){return{"/":L6(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new r(n,i,s,o||U6(n,i,s.bytes))}else if(t[MO]===!0){let{version:n,multihash:i,code:s}=t,o=Ui(i);return r.create(n,s,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==pl)throw new Error(`Version 0 CID must use dag-pb (code: ${pl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=U6(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,pl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=ls(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new ra(t.multihashCode,t.digestSize,s,i);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=dl(e.subarray(t));return t+=h,f},i=n(),s=pl;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),u=t+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=NO(e,t),s=r.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return q2(s).set(n,e),s}},NO=(r,e)=>{switch(r[0]){case"Q":{let t=e||Re;return[Re.prefix,t.decode(`${Re.prefix}${r}`)]}case Re.prefix:{let t=e||Re;return[Re.prefix,t.decode(r)]}case Zt.prefix:{let t=e||Zt;return[Zt.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},OO=(r,e,t)=>{let{prefix:n}=t;if(n!==Re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},BO=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},pl=112,LO=18,U6=(r,e,t)=>{let n=lc(r),i=n+lc(e),s=new Uint8Array(i+t.byteLength);return uc(r,s,0),uc(e,s,n),s.set(t,i),s},MO=Symbol.for("@ipld/js-cid/CID");var Kh=85;var ml=class extends ta{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Zt.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Zt.encode(e.multihash.bytes));if(t==null)throw fl();return t}has(e){return this.data.has(Zt.encode(e.multihash.bytes))}async delete(e){this.data.delete(Zt.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:Ne.createV1(Kh,Ui(Zt.decode(e))),block:t}}};function UO(r){return r[Symbol.asyncIterator]!=null}function FO(r){if(UO(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Wr=FO;function KO(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var fc=KO;function VO(r){return r[Symbol.asyncIterator]!=null}function qO(r,e){if(VO(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=fc(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let o=e;return function*(){s===!0&&(yield n);for(let a of t)o(a)&&(yield a)}()}var Lr=qO;function Le(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Vh=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},hc=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Vh(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Vh(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var $2=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Pt(r={}){return K6(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function F6(r={}){return K6(t=>{let n,i=[];for(;!t.isEmpty()&&(n=t.shift(),n!=null);){if(n.error!=null)throw n.error;n.done===!1&&i.push(n.value)}return n==null?{done:!0}:{done:n.done===!0,value:i}},r)}function K6(r,e){e=e??{};let t=e.onEnd,n=new hc,i,s,o,a=Le(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(E){y(E)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Le()})}},u=g=>s!=null?s(g):(n.push(g),i),l=g=>(n=new hc,s!=null?s({error:g}):(n.push({error:g}),i)),f=g=>{if(o)return i;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},h=g=>o?i:(o=!0,g!=null?l(g):u({done:!0})),d=()=>(n=new hc,h(),{done:!0}),p=g=>(h(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:h,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,E;y!=null&&(b=new Promise((_,x)=>{E=()=>{x(new $2)},y.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&y!=null&&y?.removeEventListener("abort",E)}}},t==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(g){return m.end(g),t!=null&&(t(g),t=void 0),i},get readableLength(){return m.readableLength}},i}function zO(r){return r[Symbol.asyncIterator]!=null}function $O(...r){let e=[];for(let t of r)zO(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Pt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Jt=$O;var kJ=C("blockstore:core:tiered");var LJ={...cc};var V6=j(ac(),1);function qh(r){return r=r??new Error("Not Found"),(0,V6.default)(r,"ERR_NOT_FOUND")}var q6=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");function ds(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var H2={};be(H2,{identity:()=>HO});var HO=oc({prefix:"\0",name:"identity",encode:r=>I6(r),decode:r=>R6(r)});var G2={};be(G2,{base2:()=>GO});var GO=Ct({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var W2={};be(W2,{base8:()=>WO});var WO=Ct({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Y2={};be(Y2,{base10:()=>YO});var YO=Ws({prefix:"9",name:"base10",alphabet:"0123456789"});var Q2={};be(Q2,{base16:()=>QO,base16upper:()=>XO});var QO=Ct({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),XO=Ct({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var X2={};be(X2,{base36:()=>yl,base36upper:()=>jO});var yl=Ws({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),jO=Ws({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var j2={};be(j2,{base256emoji:()=>rB});var z6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),ZO=z6.reduce((r,e,t)=>(r[t]=e,r),[]),JO=z6.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function eB(r){return r.reduce((e,t)=>(e+=ZO[t],e),"")}function tB(r){let e=[];for(let t of r){let n=JO[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var rB=oc({prefix:"\u{1F680}",name:"base256emoji",encode:eB,decode:tB});var tm={};be(tm,{sha256:()=>Ke,sha512:()=>em});var J2=({name:r,code:e,encode:t})=>new Z2(r,e,t),Z2=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?ii(this.code,t):t.then(n=>ii(this.code,n))}else throw Error("Unknown type, must be binary type")}};var H6=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ke=J2({name:"sha2-256",code:18,encode:H6("SHA-256")}),em=J2({name:"sha2-512",code:19,encode:H6("SHA-512")});var rm={};be(rm,{identity:()=>Fi});var G6=0,nB="identity",W6=ls,iB=r=>ii(G6,W6(r)),Fi={code:G6,name:nB,encode:W6,digest:iB};var eee=new TextEncoder,tee=new TextDecoder;var Bn={...H2,...G2,...W2,...Y2,...Q2,...L2,...X2,...M2,...F2,...j2},oee={...tm,...rm};function ps(r=0){return globalThis.Buffer?.alloc!=null?ds(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Mr(r=0){return globalThis.Buffer?.allocUnsafe!=null?ds(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Q6(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Y6=Q6("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),nm=Q6("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);let e=Mr(r.length);for(let t=0;t1&&this._buf[this._buf.byteLength-1]===$h;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;io)return!1}return t.lengtht.namespaces()))])}};function aB(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function cB(r){let e=r.split(":");return e[e.length-1]}function uB(r){return[].concat(...r)}var j6="SHARDING";function fB(r){return r[Symbol.asyncIterator]!=null}function hB(r){if(fB(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var bl=hB;function dB(r){return r[Symbol.asyncIterator]!=null}function pB(r,e){return dB(r)?async function*(){yield*(await bl(r)).sort(e)}():function*(){yield*bl(r).sort(e)}()}var Hh=pB;function mB(r){return r[Symbol.asyncIterator]!=null}function gB(r,e){return mB(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var Ys=gB;var gs=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Wr(this.putMany(e,n)),e=[],await Wr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=Lr(n,s=>s.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Lr(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Hh(i,s),n)),e.offset!=null){let i=0,s=e.offset;n=Lr(n,()=>i++>=s)}return e.limit!=null&&(n=Ys(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=Lr(n,s=>s.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Lr(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>Hh(i,s),n)),e.offset!=null){let i=e.offset,s=0;n=Lr(n,()=>s++>=i)}return e.limit!=null&&(n=Ys(n,e.limit)),n}};var na=class extends gs{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw qh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new pt(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new pt(e)}};function yB(r){return r[Symbol.asyncIterator]!=null}function bB(r,e){if(yB(r))return async function*(){for await(let a of r)yield e(a)}();let t=fc(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of t)yield e(a)}();let o=e;return function*(){yield s;for(let a of t)yield o(a)}()}var oi=bB;function Me(r,...e){if(r==null)throw new Error("Empty pipeline");if(im(r)){let n=r;r=()=>n.source}else if(J6(r)||Z6(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&im(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n{let e;for(;r.length>0;)e=r.shift()(e);return e},Z6=r=>r?.[Symbol.asyncIterator]!=null,J6=r=>r?.[Symbol.iterator]!=null,im=r=>r==null?!1:r.sink!=null&&r.source!=null,EB=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Pt({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,s=r.source;if(Z6(s))i=async function*(){yield*s,n.end()};else if(J6(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Jt(n,i())}return r.source};var Zee=new pt(j6);var lte=C("datastore:core:tiered");function er(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}function _B(r){return r[Symbol.asyncIterator]!=null}function SB(r,e){if(_B(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=fc(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let o=e;return function*(){yield n;for(let a of t)o(a),yield a}()}var ia=SB;var sm=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ki(r){let{name:e,metrics:t}=r,n;return t!=null?n=new sm({name:e,metrics:t}):n=new Map,n}var ai=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},w=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},wl=class r extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=r.code}static code="ERR_UNEXPECTED_PEER"},sa=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var p9=j(p7(),1);function fe(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t0}get[Symbol.toStringTag](){return`WantlistEntry `}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var Qs=class{entry;cancel;sendDontHave;constructor(e,t,n,i,s){this.entry=new oa(e,t,n),this.cancel=!!i,this.sendDontHave=!!s}get cid(){return this.entry.cid}set cid(e){this.entry.cid=e}get priority(){return this.entry.priority}set priority(e){this.entry.priority=e}get wantType(){return this.entry.wantType}set wantType(e){this.entry.wantType=e}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(Re)} `}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var Ln=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),C(t.join(":"))};var Gh=(r,e)=>{if(r.size!==e.size)return!1;for(let[t,n]of r){let i=e.get(t);if(i===void 0||n instanceof Uint8Array&&i instanceof Uint8Array&&!fe(n,i)||n instanceof Qs&&i instanceof Qs&&!n.equals(i))return!1}return!0};var El=j(S7(),1);function jB(r){let e=new Uint8Array(r.reduce((n,i)=>n+El.default.encodingLength(i),0)),t=0;for(let n of r)e=El.encode(n,e,t),t+=El.default.encodingLength(n);return e}var R7=jB;var xm=j(Xh(),1),l9=j(dm(),1),f9=j(ys(),1),vm=j(Zh(),1),h9=j(Em(),1);function oL(){f9.default._configure(),xm.default._configure(l9.default),vm.default._configure(h9.default)}oL();var d9=["uint64","int64","sint64","fixed64","sfixed64"];function aL(r){for(let e of d9){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function _m(r){return aL(new xm.default(r))}function cL(r){for(let e of d9){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function Sm(){return cL(vm.default.create())}function de(r,e){let t=_m(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function pe(r,e){let t=Sm();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var pc;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(pc||(pc={}));function Jh(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function ft(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return Jh("enum",pc.VARINT,t,n)}function me(r,e){return Jh("message",pc.LENGTH_DELIMITED,r,e)}var Yr;(function(r){let e;(function(a){let c;(function(h){h.Block="Block",h.Have="Have"})(c=a.WantType||(a.WantType={}));let u;(function(h){h[h.Block=0]="Block",h[h.Have=1]="Have"})(u||(u={})),function(h){h.codec=()=>ft(u)}(c=a.WantType||(a.WantType={}));let l;(function(h){let d;h.codec=()=>(d==null&&(d=me((p,m,g={})=>{g.lengthDelimited!==!1&&m.fork(),p.block!=null&&p.block.byteLength>0&&(m.uint32(10),m.bytes(p.block)),p.priority!=null&&p.priority!==0&&(m.uint32(16),m.int32(p.priority)),p.cancel!=null&&p.cancel!==!1&&(m.uint32(24),m.bool(p.cancel)),p.wantType!=null&&u[p.wantType]!==0&&(m.uint32(32),r.Wantlist.WantType.codec().encode(p.wantType,m)),p.sendDontHave!=null&&p.sendDontHave!==!1&&(m.uint32(40),m.bool(p.sendDontHave)),g.lengthDelimited!==!1&&m.ldelim()},(p,m)=>{let g={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},y=m==null?p.len:p.pos+m;for(;p.pos>>3){case 1:g.block=p.bytes();break;case 2:g.priority=p.int32();break;case 3:g.cancel=p.bool();break;case 4:g.wantType=r.Wantlist.WantType.codec().decode(p);break;case 5:g.sendDontHave=p.bool();break;default:p.skipType(b&7);break}}return g})),d),h.encode=p=>pe(p,h.codec()),h.decode=p=>de(p,h.codec())})(l=a.Entry||(a.Entry={}));let f;a.codec=()=>(f==null&&(f=me((h,d,p={})=>{if(p.lengthDelimited!==!1&&d.fork(),h.entries!=null)for(let m of h.entries)d.uint32(10),r.Wantlist.Entry.codec().encode(m,d);h.full!=null&&h.full!==!1&&(d.uint32(16),d.bool(h.full)),p.lengthDelimited!==!1&&d.ldelim()},(h,d)=>{let p={entries:[],full:!1},m=d==null?h.len:h.pos+d;for(;h.pos>>3){case 1:p.entries.push(r.Wantlist.Entry.codec().decode(h,h.uint32()));break;case 2:p.full=h.bool();break;default:h.skipType(g&7);break}}return p})),f),a.encode=h=>pe(h,a.codec()),a.decode=h=>de(h,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=me((u,l,f={})=>{f.lengthDelimited!==!1&&l.fork(),u.prefix!=null&&u.prefix.byteLength>0&&(l.uint32(10),l.bytes(u.prefix)),u.data!=null&&u.data.byteLength>0&&(l.uint32(18),l.bytes(u.data)),f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={prefix:new Uint8Array(0),data:new Uint8Array(0)},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.prefix=u.bytes();break;case 2:f.data=u.bytes();break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>pe(u,a.codec()),a.decode=u=>de(u,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>ft(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=me((u,l,f={})=>{f.lengthDelimited!==!1&&l.fork(),u.cid!=null&&u.cid.byteLength>0&&(l.uint32(10),l.bytes(u.cid)),u.type!=null&&i[u.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(u.type,l)),f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={cid:new Uint8Array(0),type:n.Have},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.cid=u.bytes();break;case 2:f.type=r.BlockPresenceType.codec().decode(u);break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>pe(u,a.codec()),a.decode=u=>de(u,a.codec())})(s=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=me((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let l of a.blocks)c.uint32(18),c.bytes(l);if(a.payload!=null)for(let l of a.payload)c.uint32(26),r.Block.codec().encode(l,c);if(a.blockPresences!=null)for(let l of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(l,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=c==null?a.len:a.pos+c;for(;a.pos>>3){case 1:u.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:u.blocks.push(a.bytes());break;case 3:u.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:u.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:u.pendingBytes=a.int32();break;default:a.skipType(f&7);break}}return u})),o),r.encode=a=>pe(a,r.codec()),r.decode=a=>de(a,r.codec())})(Yr||(Yr={}));var Dr=class r{static Entry=Qs;static WantType={Block:Yr.Wantlist.WantType.Block,Have:Yr.Wantlist.WantType.Have};static BlockPresenceType={Have:Yr.BlockPresenceType.Have,DontHave:Yr.BlockPresenceType.DontHave};static deserialize=async(e,t)=>{let n=Yr.decode(e),i=n.wantlist?.full===!0,s=new r(i);return n.wantlist?.entries.forEach(o=>{if(o.block==null)return;let a=Ne.decode(o.block);s.addEntry(a,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),n.blockPresences.forEach(o=>{if(o.cid==null)return;let a=Ne.decode(o.cid);o.type===r.BlockPresenceType.Have?s.addHave(a):s.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async o=>{let a=await Ke.digest(o),c=Ne.createV0(a);s.addBlock(c,o)})),s):(n.payload.length>0&&(await Promise.all(n.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let a=(0,p9.default)(o.prefix),c=a[0],u=a[1],l=a[2],f=l===Ke.code?Ke:await t?.getHasher(l);if(f==null)throw new w("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let h=await f.digest(o.data),d=Ne.create(c,u,h);s.addBlock(d,o.data)})),s.setPendingBytes(n.pendingBytes)),s)};static blockPresenceSize=e=>e.bytes.length+1;full;wantlist;blocks;blockPresences;pendingBytes;constructor(e){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(e,t,n,i,s){n==null&&(n=r.WantType.Block);let o=e.toString(Re),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),s===!0&&(a.sendDontHave=!!s),n===r.WantType.Block&&a.wantType===r.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new Qs(e,t,n,i,s))}addBlock(e,t){let n=e.toString(Re);this.blocks.set(n,t)}addHave(e){let t=e.toString(Re);this.blockPresences.has(t)||this.blockPresences.set(t,r.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(Re);this.blockPresences.has(t)||this.blockPresences.set(t,r.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(Re);this.wantlist.delete(t),this.addEntry(e,0,r.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return Yr.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:Yr.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let e={wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),wantType:t.wantType,cancel:!!t.cancel,sendDontHave:!!t.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=Ne.parse(t),s=i.version,o=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=R7([s,o,a,c]);e.payload.push({prefix:u,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:Ne.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),Yr.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!Gh(this.wantlist,e.wantlist)||!Gh(this.blocks,e.blocks)||!Gh(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage `}};var m9={Block:Yr.Wantlist.WantType.Block,Have:Yr.Wantlist.WantType.Have},uL=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),s=r(n);return is?1:0}),Zs=class{static Entry=oa;set;_stats;constructor(e,t){this.set=t!=null?Ki({name:"ipfs_bitswap_wantlist",metrics:t.metrics}):new Map,this._stats=e}get length(){return this.set.size}add(e,t,n){let i=e.toString(Re),s=this.set.get(i);s!=null?(s.inc(),s.priority=t,s.wantType===m9.Have&&n===m9.Block&&(s.wantType=n)):(this.set.set(i,new oa(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(Re),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(uL(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(Re);return this.set.has(t)}get(e){let t=e.toString(Re);return this.set.get(t)}};var e0=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(e){this.partner=e,this.wantlist=new Zs,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=e}wants(e,t,n){this.wantlist.add(e,t,n)}cancelWant(e){this.wantlist.remove(e)}wantlistContains(e){return this.wantlist.get(e)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var _l=class extends Map{_cmp;_keys;constructor(e,t){super(),this._cmp=t??this._defaultSort,this._keys=[];for(let[n,i]of e??[])this.set(n,i)}update(e){if(e<0||e>=this._keys.length)return;let t=this._keys[e];this._keys.splice(e,1);let n=this._find(t);this._keys.splice(n,0,t)}set(e,t){if(this.has(e)){let i=this.indexOf(e);this._keys.splice(i,1)}super.set(e,t);let n=this._find(e);return this._keys.splice(n,0,e),this}clear(){super.clear(),this._keys=[]}delete(e){if(!this.has(e))return!1;let t=this.indexOf(e);return this._keys.splice(t,1),super.delete(e)}indexOf(e){if(!this.has(e))return-1;let t=this._find(e);if(this._keys[t]===e)return t;for(let n=1;n>>1,s=this._kCmp(this._keys[i],e);if(s<0)t=i+1;else if(s>0)n=i;else return i}return t}*keys(){for(let e of this._keys)yield e}*values(){for(let e of this._keys)yield this.get(e)}*entries(){for(let e of this._keys)yield[e,this.get(e)]}*[Symbol.iterator](){yield*this.entries()}forEach(e,t=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]t.priority&&this._pending.updatePriority(e.topic,e.priority),this._taskMerger.merge(e,t);return}this._pending.add(e)}_taskHasMoreInfoThanActiveTasks(e){let t=[];for(let n of this._active)n.topic===e.topic&&t.push(n);return t.length===0?!0:this._taskMerger.hasNewInfo(e,t)}popTasks(e){let t=0,n=[],i=this._pending.tasks();for(let s=0;se+t.task.size,0)}get(e){return this._tasks?.get(e)?.task}add(e){this._tasks.set(e.topic,{created:Date.now(),task:e})}delete(e){this._tasks.delete(e)}tasks(){return[...this._tasks.values()].map(e=>e.task)}updatePriority(e,t){let n=this._tasks.get(e);if(n==null)return;let i=this._tasks.indexOf(e);n.task.priority=t,this._tasks.update(i)}_compare(e,t){return e[1].task.priority===t[1].task.priority?e[1].created-t[1].created:t[1].task.priority-e[1].task.priority}};var g9={hasNewInfo(r,e){let t=!1,n=!1;for(let i of e)i.data.haveBlock&&(t=!0),i.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!t&&r.data.haveBlock)},merge(r,e){let t=r.data,n=e.data;!n.haveBlock&&t.haveBlock&&(n.haveBlock=t.haveBlock,n.blockSize=t.blockSize),!n.isWantBlock&&t.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||t.haveBlock)&&(n.haveBlock=t.haveBlock,e.size=r.size)),n.isWantBlock&&n.haveBlock&&(e.size=n.blockSize)}};var y9=Dr.WantType,fL=16*1024,hL=1024,n0=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(e,t,n,i,s,o={}){this._log=Ln(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(o),this.ledgerMap=Ki({name:"ipfs_bitswap_ledger_map",metrics:s.metrics}),this._running=!1,this._requestQueue=new t0(g9)}_processOpts(e){return{maxSizeReplaceHasWithBlock:hL,targetMessageSize:fL,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}async _processTasks(){if(!this._running)return;let{peerId:e,tasks:t,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(t.length===0)return;let i=new Dr(!1);i.setPendingBytes(n);let s=[],o=new Map;for(let c of t){let u=Ne.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(s.push(u),o.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(s);for(let[c,u]of o){let l=Ne.parse(c),f=a.get(c);f!=null?i.addBlock(l,f):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e!=null&&this.messageSent(e,Ne.parse(c),u)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let s=t.wantlistContains(n);if(s==null)continue;let o=i.length,a=this._sendAsBlock(s.wantType,o),c=o;a||(c=Dr.blockPresenceSize(s.cid)),this._requestQueue.pushTasks(t.partner,[{topic:s.cid.toString(Re),priority:s.priority,size:c,data:{blockSize:o,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(e,t){let n=this._findOrCreate(e);if(t.empty)return;if(t.full&&(n.wantlist=new Zs),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],s=[];t.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),i.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),s.push(o))}),this._cancelWants(e,i),await this._addWants(e,s),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(Re),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(s=>s.cid)),i=[];for(let s of t){let o=s.cid.toString(Re),a=n.get(o);if(a==null)s.sendDontHave&&i.push({topic:o,priority:s.priority,size:Dr.blockPresenceSize(s.cid),data:{isWantBlock:s.wantType===y9.Block,blockSize:0,haveBlock:!1,sendDontHave:s.sendDontHave}});else{let c=this._sendAsBlock(s.wantType,a),u=a;c||(u=Dr.blockPresenceSize(s.cid)),i.push({topic:o,priority:s.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:s.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===y9.Block||t<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(e){let t=await this._getBlocks(e);return new Map([...t].map(([n,i])=>[n,i.length]))}async _getBlocks(e){let t=new Map;return await Promise.all(e.map(async n=>{try{let i=await this.blockstore.get(n);t.set(n.toString(Re),i)}catch(i){i.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,i)}})),t}_updateBlockAccounting(e,t){for(let n of e.values())this._log("got block (%s bytes)",n.length),t.receivedBytes(n.length)}messageSent(e,t,n){let i=this._findOrCreate(e);i.sentBytes(n.length),i.wantlist.remove(t)}numBytesSentTo(e){return this._findOrCreate(e).accounting.bytesSent}numBytesReceivedFrom(e){return this._findOrCreate(e).accounting.bytesRecv}peerDisconnected(e){this.ledgerMap.delete(e.toString())}_findOrCreate(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return n;let i=new e0(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var dL=Math.pow(2,7),pL=Math.pow(2,14),mL=Math.pow(2,21),Im=Math.pow(2,28),Am=Math.pow(2,35),Tm=Math.pow(2,42),Dm=Math.pow(2,49),tt=128,Cr=127;function sr(r){if(rNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function gL(r,e,t=0){switch(sr(r)){case 8:e[t++]=r&255|tt,r/=128;case 7:e[t++]=r&255|tt,r/=128;case 6:e[t++]=r&255|tt,r/=128;case 5:e[t++]=r&255|tt,r/=128;case 4:e[t++]=r&255|tt,r>>>=7;case 3:e[t++]=r&255|tt,r>>>=7;case 2:e[t++]=r&255|tt,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function yL(r,e,t=0){switch(sr(r)){case 8:e.set(t++,r&255|tt),r/=128;case 7:e.set(t++,r&255|tt),r/=128;case 6:e.set(t++,r&255|tt),r/=128;case 5:e.set(t++,r&255|tt),r/=128;case 4:e.set(t++,r&255|tt),r>>>=7;case 3:e.set(t++,r&255|tt),r>>>=7;case 2:e.set(t++,r&255|tt),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function bL(r,e){let t=r[e],n=0;if(n+=t&Cr,ti+s.length,0));let t=Mr(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return ds(t)}var w9=Symbol.for("@achingbrain/uint8arraylist");function b9(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(i0(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(i0(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=b9(this.bufs,e);return t.buf[t.index]}set(e,t){let n=b9(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return ve(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:ve(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new r;return s.length=i,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s=c)continue;let u=e>=a&&ea&&t<=c;if(u&&l){if(e===a&&t===c){n.push(o);break}let f=e-a;n.push(o.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(l){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!i0(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let f=0;f=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Mr(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=ps(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=ps(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=ps(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Mr(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=ps(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=ps(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=ps(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=ps(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=ps(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;ti+s.byteLength,0)),n.length=t,n}};function s0(r){return r[Symbol.asyncIterator]!=null}var o0=r=>{let e=sr(r),t=Mr(e);return Qr(r,t),o0.bytes=e,t};o0.bytes=0;function Kt(r,e){e=e??{};let t=e.lengthEncoder??o0;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return s0(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Kt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??o0;return new Te(t(r.byteLength),r)};var mc=j(ac(),1);var EL=8,xL=1024*1024*4,la;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(la||(la={}));var Cm=r=>{let e=on(r);return Cm.bytes=sr(e),e};Cm.bytes=0;function Yt(r,e){let t=new Te,n=la.LENGTH,i=-1,s=e?.lengthDecoder??Cm,o=e?.maxLengthLength??EL,a=e?.maxDataLength??xL;function*c(){for(;t.byteLength>0;){if(n===la.LENGTH)try{if(i=s(t),i<0)throw(0,mc.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,mc.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=la.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw(0,mc.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===la.DATA){if(t.byteLength0)throw(0,mc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,mc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Yt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Yt(n,{...e??{},onLength:s=>{t=s}})};var Qe=class extends Event{constructor(e,t){super(e),this.detail=t}};var C9=j(I9(),1);var A9=Math.pow(2,31)-1,T9=1e3,D9=1;var Om="/ipfs/bitswap/1.0.0",Bm="/ipfs/bitswap/1.1.0",Lm="/ipfs/bitswap/1.2.0",RL=1024,IL=1024,AL=3e4,c0=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(e,t,n,i={}){this._log=Ln(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[Om],i.b100Only!==!0&&(this._protocols.unshift(Bm),this._protocols.unshift(Lm)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=i.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??RL,this._maxOutboundStreams=i.maxOutboundStreams??IL,this._incomingStreamTimeout=i.incomingStreamTimeout??AL}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e={onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect};this._registrarIds=[];for(let t of this._protocols)this._registrarIds.push(await this._libp2p.register(t,e));this._libp2p.getConnections().forEach(t=>{this._onPeerConnect(t.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let e of this._registrarIds)this._libp2p.unregister(e);this._registrarIds=[]}}_onConnection(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new C9.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.protocol,n.remotePeer);let s=()=>{t.abort(new w("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},o=AbortSignal.timeout(this._incomingStreamTimeout);o.addEventListener("abort",s),await Me(t,a=>Yt(a),async a=>{for await(let c of a){try{let u=await Dr.deserialize(c.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,u)}catch(u){this._bitswap._receiveError(u);break}o.removeEventListener("abort",s),o=AbortSignal.timeout(this._incomingStreamTimeout),o.addEventListener("abort",s)}}),await t.close({signal:o})}).catch(s=>{this._log(s),t.abort(s)}).finally(()=>{i.clear()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new Qe("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Wr(Ys(oi(this.findProviders(e,t),async n=>this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new Qe("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new Qe("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new Qe("bitswap:network:dial",e)),this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[Lm,Bm,Om]);try{let s;switch(i.protocol){case Om:s=t.serializeToBitswap100();break;case Bm:case Lm:s=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.protocol}`)}await Me([s],o=>Kt(o),i),await i.close()}catch(s){n.onProgress?.(new Qe("bitswap:network:send-wantlist:error",{peer:e,error:s})),this._log(s),i.abort(s)}}};var z9=j(Xr(),1);var V9=r=>`unwant:${U(r.multihash.bytes,"base64")}`,q9=r=>`block:${U(r.multihash.bytes,"base64")}`,f0=class extends z9.EventEmitter{_log;constructor(e){super(),this.setMaxListeners(T9),this._log=Ln(e,"notif")}hasBlock(e,t){let n=q9(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=q9(e),i=V9(e);return this._log(`wantBlock:${e}`),new Promise((s,o)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new Qe("bitswap:want-block:unwant",e)),o(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),t.onProgress?.(new Qe("bitswap:want-block:block",e)),s(u)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),o(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=V9(e);this._log(t),this.emit(t)}};var Q9=j(Xr(),1);var W9=j(Xr(),1),Um=j(G9(),1),Sl=class extends W9.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;constructor(e,t){super(),this._options=t,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),e.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(i=>{(this._movingAverages[n][i]=(0,Um.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(e,t){this._enabled&&(this._queue.push([e,t,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let e=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-e),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,t,e)}),this._frequencyLastTime=e}_updateFrequencyFor(e,t,n){let i=this._frequencyAccumulators[e]??0;this._frequencyAccumulators[e]=0;let s=i/t*1e3,o=this._movingAverages[e];o==null&&(o=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=o[a];c==null&&(c=o[a]=(0,Um.default)(a)),c.push(n,s)})}_applyOp(e){let t=e[0],n=e[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,t)||(this._stats[t]=BigInt(0)),this._stats[t]=BigInt(this._stats[t])+BigInt(n),this._frequencyAccumulators[t]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var Y9={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},h0=class extends Q9.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(e,t=[],n=Y9){super();let i=Object.assign({},Y9,n);if(typeof i.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof i.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=t,this._options=i,this._enabled=this._options.enabled,this._global=new Sl(t,i),this._global.on("update",s=>this.emit("update",s)),this._peers=Ki({name:"ipfs_bitswap_stats_peers",metrics:e.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let e of this._peers)e[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(e){let t=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new Sl(this._initialCounters,this._options),this._peers.set(e,i)),i.push(t,n)}}disconnected(e){let t=e.toString(),n=this._peers.get(t);n!=null&&(n.stop(),this._peers.delete(t))}};var X9=BL;function BL(r,e,t){var n=null,i=null,s=function(){n&&(clearTimeout(n),i=null,n=null)},o=function(){var c=i;s(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,u=arguments,l=t&&!n;if(s(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var f=i;return i=null,f()}},e),l)return i()};return a.cancel=s,a.flush=o,a}var d0=class{peerId;refcnt;network;_entries;_log;constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=Ln(e,"msgqueue"),this.sendEntries=X9(this.sendEntries.bind(this),D9)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new Dr(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var p0=class{peers;wantlist;network;_peerId;_log;constructor(e,t,n,i){this.peers=Ki({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new Zs(n,i),this.network=t,this._peerId=e,this._log=Ln(e,"want")}_addEntries(e,t,n,i={}){let s=e.map((o,a)=>new Dr.Entry(o,A9-a,Dr.WantType.Block,t));s.forEach(o=>{o.cancel?n===!0?this.wantlist.removeForce(o.cid.toString(Re)):this.wantlist.remove(o.cid):(this._log("adding to wantlist"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(s,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new d0(this._peerId,e,this.network);let n=new Dr(!0);for(let i of this.wantlist.entries())n.addEntry(i[1].cid,i[1].priority);return t.addMessage(n),this.peers.set(e.toString(),t),t}_stopPeerHandler(e){let t=this.peers.get(e.toString());t!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),t.signal?.addEventListener("abort",()=>{this.cancelWants(e)})}unwantBlocks(e){this._log("unwant blocks: %s",e.length),this._addEntries(e,!0,!0)}cancelWants(e){this._log("cancel wants: %s",e.length),this._addEntries(e,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(e){this._startPeerHandler(e)}disconnected(e){this._stopPeerHandler(e)}start(){}stop(){this.peers.forEach(e=>{this.disconnected(e.peerId)})}};var LL={async getHasher(){throw new Error("Not implemented")}},ML={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:LL,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},UL=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],m0=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(e,t,n={}){this._libp2p=e,this._log=Ln(this.peerId),n=Object.assign({},ML,n),this.stats=new h0(e,UL,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new c0(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new n0(this.peerId,t,this.network,this.stats,e),this.wm=new p0(this.peerId,this.network,this.stats,e),this.notifications=new f0(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(e,t){try{await this.engine.messageReceived(e,t)}catch{this._log("failed to receive message",t)}if(t.blocks.size===0)return;let n=[];for(let[i,s]of t.blocks.entries()){let o=Ne.parse(i);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:s})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:s,data:o})=>{await this._handleReceivedBlock(e,i,o,s)}))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let s=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,s),i&&await this.put(t,n)}_updateReceiveCounters(e,t,n,i){this.stats.push(e,"blocksReceived",1),this.stats.push(e,"dataReceived",n.length),i&&(this.stats.push(e,"dupBlksReceived",1),this.stats.push(e,"dupDataReceived",n.length))}_receiveError(e){this._log.error("ReceiveError",e)}_onPeerConnected(e){this.wm.connected(e)}_onPeerDisconnected(e){this.wm.disconnected(e),this.engine.peerDisconnected(e),this.stats.disconnected(e)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(e,t){return this.engine.wantlistForPeer(e)}ledgerForPeer(e){return this.engine.ledgerForPeer(e)}async want(e,t={}){let n=async(c,u)=>(this.wm.wantBlocks([c],u),this.notifications.wantBlock(c,u)),i=!1,s=async(c,u)=>{try{return await this.blockstore.get(c,u)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l;return i||(i=!0,this.network.findAndConnect(c,u).catch(f=>{this._log.error(f)})),await n(c,u)}},o=new AbortController,a=er([o.signal,t.signal]);try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),s(e,{...t,signal:a})])}finally{o.abort(),a.clear()}}unwant(e){let t=Array.isArray(e)?e:[e];this.wm.unwantBlocks(t),t.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(e){this.wm.cancelWants(Array.isArray(e)?e:[e])}async put(e,t,n){await this.blockstore.put(e,t),this.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(ia(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this.stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}};var j9=(r,e,t={})=>new m0(r,e,t);var FL=["string","number","bigint","symbol"],KL=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Z9(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(FL.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(VL(r))return"Buffer";let t=qL(r);return t||"Object"}function VL(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function qL(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(KL.includes(e))return e}var I=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};I.uint=new I(0,"uint",!0);I.negint=new I(1,"negint",!0);I.bytes=new I(2,"bytes",!0);I.string=new I(3,"string",!0);I.array=new I(4,"array",!1);I.map=new I(5,"map",!1);I.tag=new I(6,"tag",!1);I.float=new I(7,"float",!0);I.false=new I(7,"false",!0);I.true=new I(7,"true",!0);I.null=new I(7,"null",!0);I.undefined=new I(7,"undefined",!0);I.break=new I(7,"break",!0);var W=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var yc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",zL=new TextDecoder,$L=new TextEncoder;function g0(r){return yc&&globalThis.Buffer.isBuffer(r)}function Rl(r){return r instanceof Uint8Array?g0(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var rb=yc?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):eb(r,e,t):(r,e,t)=>t-e>64?zL.decode(r.subarray(e,t)):eb(r,e,t),y0=yc?r=>r.length>64?globalThis.Buffer.from(r):J9(r):r=>r.length>64?$L.encode(r):J9(r),zi=r=>Uint8Array.from(r),bc=yc?(r,e,t)=>g0(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),nb=yc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Rl(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},ib=yc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function sb(r,e){if(g0(r)&&g0(e))return r.compare(e);for(let t=0;t55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function eb(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+o<=t){let a,c,u,l;switch(o){case 1:i<128&&(s=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(s=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(s=l))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=o}return Fm(n)}var tb=4096;function Fm(r){let e=r.length;if(e<=tb)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=bc(n,0,this.cursor)}else t=nb(this.chunks,this.cursor);return e&&this.reset(),t}};var ce="CBOR decode error:",wc="CBOR encode error:",Al=[];Al[23]=1;Al[24]=2;Al[25]=3;Al[26]=5;Al[27]=9;function bs(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${ce} encountered BigInt larger than allowable range`)}}Un.encodedSize=function(e){return gr.encodedSize(e.value)};gr.encodedSize=function(e){return et.value?1:0};function lb(r,e,t,n){return new W(I.negint,-1-an(r,e+1,n),2)}function fb(r,e,t,n){return new W(I.negint,-1-cn(r,e+1,n),3)}function hb(r,e,t,n){return new W(I.negint,-1-un(r,e+1,n),5)}var Km=BigInt(-1),db=BigInt(1);function pb(r,e,t,n){let i=ln(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new W(I.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${ce} integers outside of the safe integer range are not supported`);return new W(I.negint,Km-BigInt(i),9)}function b0(r,e){let t=e.value,n=typeof t=="bigint"?t*Km-db:t*-1-1;gr(r,e.type.majorEncoded,n)}b0.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Km-db:t*-1-1;return nt.value?-1:0};function Tl(r,e,t,n){bs(r,e,t+n);let i=bc(r,e+t,e+t+n);return new W(I.bytes,i,t+n)}function mb(r,e,t,n){return Tl(r,e,1,t)}function gb(r,e,t,n){return Tl(r,e,2,an(r,e+1,n))}function yb(r,e,t,n){return Tl(r,e,3,cn(r,e+1,n))}function bb(r,e,t,n){return Tl(r,e,5,un(r,e+1,n))}function wb(r,e,t,n){let i=ln(r,e+1,n);if(typeof i=="bigint")throw new Error(`${ce} 64-bit integer bytes lengths not supported`);return Tl(r,e,9,i)}function w0(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===I.string?y0(r.value):r.value),r.encodedBytes}function Ec(r,e){let t=w0(e);gr(r,e.type.majorEncoded,t.length),r.push(t)}Ec.encodedSize=function(e){let t=w0(e);return gr.encodedSize(t.length)+t.length};Ec.compareTokens=function(e,t){return WL(w0(e),w0(t))};function WL(r,e){return r.lengthe.length?1:sb(r,e)}function Dl(r,e,t,n,i){let s=t+n;bs(r,e,s);let o=new W(I.string,rb(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=bc(r,e+t,e+s)),o}function Eb(r,e,t,n){return Dl(r,e,1,t,n)}function xb(r,e,t,n){return Dl(r,e,2,an(r,e+1,n),n)}function vb(r,e,t,n){return Dl(r,e,3,cn(r,e+1,n),n)}function _b(r,e,t,n){return Dl(r,e,5,un(r,e+1,n),n)}function Sb(r,e,t,n){let i=ln(r,e+1,n);if(typeof i=="bigint")throw new Error(`${ce} 64-bit integer string lengths not supported`);return Dl(r,e,9,i,n)}var Rb=Ec;function xc(r,e,t,n){return new W(I.array,n,t)}function Ib(r,e,t,n){return xc(r,e,1,t)}function Ab(r,e,t,n){return xc(r,e,2,an(r,e+1,n))}function Tb(r,e,t,n){return xc(r,e,3,cn(r,e+1,n))}function Db(r,e,t,n){return xc(r,e,5,un(r,e+1,n))}function Cb(r,e,t,n){let i=ln(r,e+1,n);if(typeof i=="bigint")throw new Error(`${ce} 64-bit integer array lengths not supported`);return xc(r,e,9,i)}function Pb(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ce} indefinite length items not allowed`);return xc(r,e,1,1/0)}function E0(r,e){gr(r,I.array.majorEncoded,e.value)}E0.compareTokens=Un.compareTokens;E0.encodedSize=function(e){return gr.encodedSize(e.value)};function vc(r,e,t,n){return new W(I.map,n,t)}function kb(r,e,t,n){return vc(r,e,1,t)}function Nb(r,e,t,n){return vc(r,e,2,an(r,e+1,n))}function Ob(r,e,t,n){return vc(r,e,3,cn(r,e+1,n))}function Bb(r,e,t,n){return vc(r,e,5,un(r,e+1,n))}function Lb(r,e,t,n){let i=ln(r,e+1,n);if(typeof i=="bigint")throw new Error(`${ce} 64-bit integer map lengths not supported`);return vc(r,e,9,i)}function Mb(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ce} indefinite length items not allowed`);return vc(r,e,1,1/0)}function x0(r,e){gr(r,I.map.majorEncoded,e.value)}x0.compareTokens=Un.compareTokens;x0.encodedSize=function(e){return gr.encodedSize(e.value)};function Ub(r,e,t,n){return new W(I.tag,t,1)}function Fb(r,e,t,n){return new W(I.tag,an(r,e+1,n),2)}function Kb(r,e,t,n){return new W(I.tag,cn(r,e+1,n),3)}function Vb(r,e,t,n){return new W(I.tag,un(r,e+1,n),5)}function qb(r,e,t,n){return new W(I.tag,ln(r,e+1,n),9)}function v0(r,e){gr(r,I.tag.majorEncoded,e.value)}v0.compareTokens=Un.compareTokens;v0.encodedSize=function(e){return gr.encodedSize(e.value)};var JL=20,eM=21,tM=22,rM=23;function zb(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ce} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new W(I.null,null,1):new W(I.undefined,void 0,1)}function $b(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ce} indefinite length items not allowed`);return new W(I.break,void 0,1)}function Vm(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ce} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ce} Infinity values are not supported`)}return new W(I.float,r,e)}function Hb(r,e,t,n){return Vm(qm(r,e+1),3,n)}function Gb(r,e,t,n){return Vm(zm(r,e+1),5,n)}function Wb(r,e,t,n){return Vm(jb(r,e+1),9,n)}function _0(r,e,t){let n=e.value;if(n===!1)r.push([I.float.majorEncoded|JL]);else if(n===!0)r.push([I.float.majorEncoded|eM]);else if(n===null)r.push([I.float.majorEncoded|tM]);else if(n===void 0)r.push([I.float.majorEncoded|rM]);else{let i,s=!1;(!t||t.float64!==!0)&&(Qb(n),i=qm(li,1),n===i||Number.isNaN(n)?(li[0]=249,r.push(li.slice(0,3)),s=!0):(Xb(n),i=zm(li,1),n===i&&(li[0]=250,r.push(li.slice(0,5)),s=!0))),s||(nM(n),i=jb(li,1),li[0]=251,r.push(li.slice(0,9)))}}_0.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Qb(n);let i=qm(li,1);if(n===i||Number.isNaN(n))return 3;if(Xb(n),i=zm(li,1),n===i)return 5}return 9};var Yb=new ArrayBuffer(9),Fn=new DataView(Yb,1),li=new Uint8Array(Yb,0);function Qb(r){if(r===1/0)Fn.setUint16(0,31744,!1);else if(r===-1/0)Fn.setUint16(0,64512,!1);else if(Number.isNaN(r))Fn.setUint16(0,32256,!1);else{Fn.setFloat32(0,r);let e=Fn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Fn.setUint16(0,31744,!1);else if(t===0)Fn.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Fn.setUint16(0,0):i<-14?Fn.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Fn.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function qm(r,e){if(r.length-e<2)throw new Error(`${ce} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function Xb(r){Fn.setFloat32(0,r,!1)}function zm(r,e){if(r.length-e<4)throw new Error(`${ce} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function nM(r){Fn.setFloat64(0,r,!1)}function jb(r,e){if(r.length-e<8)throw new Error(`${ce} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}_0.compareTokens=Un.compareTokens;function Xe(r,e,t){throw new Error(`${ce} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function S0(r){return()=>{throw new Error(`${ce} ${r}`)}}var Z=[];for(let r=0;r<=23;r++)Z[r]=Xe;Z[24]=ob;Z[25]=ab;Z[26]=cb;Z[27]=ub;Z[28]=Xe;Z[29]=Xe;Z[30]=Xe;Z[31]=Xe;for(let r=32;r<=55;r++)Z[r]=Xe;Z[56]=lb;Z[57]=fb;Z[58]=hb;Z[59]=pb;Z[60]=Xe;Z[61]=Xe;Z[62]=Xe;Z[63]=Xe;for(let r=64;r<=87;r++)Z[r]=mb;Z[88]=gb;Z[89]=yb;Z[90]=bb;Z[91]=wb;Z[92]=Xe;Z[93]=Xe;Z[94]=Xe;Z[95]=S0("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Z[r]=Eb;Z[120]=xb;Z[121]=vb;Z[122]=_b;Z[123]=Sb;Z[124]=Xe;Z[125]=Xe;Z[126]=Xe;Z[127]=S0("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Z[r]=Ib;Z[152]=Ab;Z[153]=Tb;Z[154]=Db;Z[155]=Cb;Z[156]=Xe;Z[157]=Xe;Z[158]=Xe;Z[159]=Pb;for(let r=160;r<=183;r++)Z[r]=kb;Z[184]=Nb;Z[185]=Ob;Z[186]=Bb;Z[187]=Lb;Z[188]=Xe;Z[189]=Xe;Z[190]=Xe;Z[191]=Mb;for(let r=192;r<=215;r++)Z[r]=Ub;Z[216]=Fb;Z[217]=Kb;Z[218]=Vb;Z[219]=qb;Z[220]=Xe;Z[221]=Xe;Z[222]=Xe;Z[223]=Xe;for(let r=224;r<=243;r++)Z[r]=S0("simple values are not supported");Z[244]=Xe;Z[245]=Xe;Z[246]=Xe;Z[247]=zb;Z[248]=S0("simple values are not supported");Z[249]=Hb;Z[250]=Gb;Z[251]=Wb;Z[252]=Xe;Z[253]=Xe;Z[254]=Xe;Z[255]=$b;var fi=[];for(let r=0;r<24;r++)fi[r]=new W(I.uint,r,1);for(let r=-1;r>=-24;r--)fi[31-r]=new W(I.negint,r,1);fi[64]=new W(I.bytes,new Uint8Array(0),1);fi[96]=new W(I.string,"",1);fi[128]=new W(I.array,0,1);fi[160]=new W(I.map,0,1);fi[244]=new W(I.false,!1,1);fi[245]=new W(I.true,!0,1);fi[246]=new W(I.null,null,1);function Zb(r){switch(r.type){case I.false:return zi([244]);case I.true:return zi([245]);case I.null:return zi([246]);case I.bytes:return r.value.length?void 0:zi([64]);case I.string:return r.value===""?zi([96]):void 0;case I.array:return r.value===0?zi([128]):void 0;case I.map:return r.value===0?zi([160]):void 0;case I.uint:return r.value<24?zi([Number(r.value)]):void 0;case I.negint:if(r.value>=-24)return zi([31-Number(r.value)])}}var sM={float64:!1,mapSorter:cM,quickEncodeToken:Zb};function oM(){let r=[];return r[I.uint.major]=Un,r[I.negint.major]=b0,r[I.bytes.major]=Ec,r[I.string.major]=Rb,r[I.array.major]=E0,r[I.map.major]=x0,r[I.tag.major]=v0,r[I.float.major]=_0,r}var Jb=oM(),$m=new Il,I0=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${wc} object contains circular references`);return new r(t,e)}},Js={null:new W(I.null,null),undefined:new W(I.undefined,void 0),true:new W(I.true,!0),false:new W(I.false,!1),emptyArray:new W(I.array,0),emptyMap:new W(I.map,0)},eo={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new W(I.float,r):r>=0?new W(I.uint,r):new W(I.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new W(I.uint,r):new W(I.negint,r)},Uint8Array(r,e,t,n){return new W(I.bytes,r)},string(r,e,t,n){return new W(I.string,r)},boolean(r,e,t,n){return r?Js.true:Js.false},null(r,e,t,n){return Js.null},undefined(r,e,t,n){return Js.undefined},ArrayBuffer(r,e,t,n){return new W(I.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new W(I.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Js.emptyArray,new W(I.break)]:Js.emptyArray;n=I0.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=R0(o,t,n);return t.addBreakTokens?[new W(I.array,r.length),i,new W(I.break)]:[new W(I.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length;if(!o)return t.addBreakTokens===!0?[Js.emptyMap,new W(I.break)]:Js.emptyMap;n=I0.createCheck(n,r);let a=[],c=0;for(let u of s)a[c++]=[R0(u,t,n),R0(i?r.get(u):r[u],t,n)];return aM(a,t),t.addBreakTokens?[new W(I.map,o),a,new W(I.break)]:[new W(I.map,o),a]}};eo.Map=eo.Object;eo.Buffer=eo.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))eo[`${r}Array`]=eo.DataView;function R0(r,e={},t){let n=Z9(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||eo[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=eo[n];if(!s)throw new Error(`${wc} unsupported type: ${n}`);return s(r,n,e,t)}function aM(r,e){e.mapSorter&&r.sort(e.mapSorter)}function cM(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,s=Jb[i].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function ew(r,e,t,n){if(Array.isArray(e))for(let i of e)ew(r,i,t,n);else t[e.type.major](r,e,n)}function tw(r,e,t){let n=R0(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let s=e[n.type.major];if(s.encodedSize){let o=s.encodedSize(n,t),a=new Il(o);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Rl(a.chunks[0])}}return $m.reset(),ew($m,n,e,t),$m.toBytes(!0)}function A0(r,e){return e=Object.assign({},sM,e),tw(r,Jb,e)}var uM={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Hm=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=fi[e];if(t===void 0){let n=Z[e];if(!n)throw new Error(`${ce} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},Cl=Symbol.for("DONE"),T0=Symbol.for("BREAK");function lM(r,e,t){let n=[];for(let i=0;iglobalThis.DOMException===void 0?new Wm(r):new DOMException(r),ow=r=>{let e=r.reason===void 0?sw("This operation was aborted."):r.reason;return e instanceof Error?e:sw(e)};function Ym(r,e,t,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(ow(c)),c.addEventListener("abort",()=>{a(ow(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Nl(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{o(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function Qm(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var da=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Es,Ol=class{constructor(){Es.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&da(this,Es,"f")[this.size-1].priority>=t.priority){da(this,Es,"f").push(n);return}let i=Qm(da(this,Es,"f"),n,(s,o)=>o.priority-s.priority);da(this,Es,"f").splice(i,0,n)}dequeue(){let e=da(this,Es,"f").shift();return e?.run}filter(e){return da(this,Es,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return da(this,Es,"f").length}};Es=new WeakMap;var It=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},ue=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Vt,Ll,Ml,ro,B0,Ul,C0,hi,Bl,fn,P0,hn,Fl,to,k0,aw,cw,fw,uw,lw,N0,Xm,jm,L0,hw,O0,M0=class extends Error{},kt=class extends dw.default{constructor(e){var t,n,i,s;if(super(),Vt.add(this),Ll.set(this,void 0),Ml.set(this,void 0),ro.set(this,0),B0.set(this,void 0),Ul.set(this,void 0),C0.set(this,0),hi.set(this,void 0),Bl.set(this,void 0),fn.set(this,void 0),P0.set(this,void 0),hn.set(this,0),Fl.set(this,void 0),to.set(this,void 0),k0.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ol,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);It(this,Ll,e.carryoverConcurrencyCount,"f"),It(this,Ml,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),It(this,B0,e.intervalCap,"f"),It(this,Ul,e.interval,"f"),It(this,fn,new e.queueClass,"f"),It(this,P0,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,It(this,k0,e.throwOnTimeout===!0,"f"),It(this,to,e.autoStart===!1,"f")}get concurrency(){return ue(this,Fl,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);It(this,Fl,e,"f"),ue(this,Vt,"m",L0).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:ue(this,k0,"f"),...t},new Promise((n,i)=>{ue(this,fn,"f").enqueue(async()=>{var s,o,a;It(this,hn,(o=ue(this,hn,"f"),o++,o),"f"),It(this,ro,(a=ue(this,ro,"f"),a++,a),"f");try{if(!((s=t.signal)===null||s===void 0)&&s.aborted)throw new M0("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=Ym(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,ue(this,Vt,"m",hw).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Nl&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{ue(this,Vt,"m",fw).call(this)}},t),this.emit("add"),ue(this,Vt,"m",N0).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return ue(this,to,"f")?(It(this,to,!1,"f"),ue(this,Vt,"m",L0).call(this),this):this}pause(){It(this,to,!0,"f")}clear(){It(this,fn,new(ue(this,P0,"f")),"f")}async onEmpty(){ue(this,fn,"f").size!==0&&await ue(this,Vt,"m",O0).call(this,"empty")}async onSizeLessThan(e){ue(this,fn,"f").sizeue(this,fn,"f").size{ue(this,Vt,"m",uw).call(this)},t),"f"),!0}return!1},N0=function(){if(ue(this,fn,"f").size===0)return ue(this,hi,"f")&&clearInterval(ue(this,hi,"f")),It(this,hi,void 0,"f"),this.emit("empty"),ue(this,hn,"f")===0&&this.emit("idle"),!1;if(!ue(this,to,"f")){let e=!ue(this,Vt,"a",lw);if(ue(this,Vt,"a",aw)&&ue(this,Vt,"a",cw)){let t=ue(this,fn,"f").dequeue();return t?(this.emit("active"),t(),e&&ue(this,Vt,"m",Xm).call(this),!0):!1}}return!1},Xm=function(){ue(this,Ml,"f")||ue(this,hi,"f")!==void 0||(It(this,hi,setInterval(()=>{ue(this,Vt,"m",jm).call(this)},ue(this,Ul,"f")),"f"),It(this,C0,Date.now()+ue(this,Ul,"f"),"f"))},jm=function(){ue(this,ro,"f")===0&&ue(this,hn,"f")===0&&ue(this,hi,"f")&&(clearInterval(ue(this,hi,"f")),It(this,hi,void 0,"f")),It(this,ro,ue(this,Ll,"f")?ue(this,hn,"f"):0,"f"),ue(this,Vt,"m",L0).call(this)},L0=function(){for(;ue(this,Vt,"m",N0).call(this););},hw=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new M0("The task was aborted."))},{once:!0})})},O0=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var pM=new TextDecoder;function Zm(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function pw(r,e){let t;return[t,e]=Zm(r,e),[t&7,t>>3,e]}function mM(r){let e={},t=r.length,n=0;for(;nt)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function mw(r){let e=r.length,t=0,n,i=!1,s;for(;te)throw new Error("protobuf: (PBNode) unexpected end of data");let o={};return s&&(o.Data=s),o.Links=n||[],o}var xse=new TextEncoder,vse=2**32,_se=2**31;var Ise=new TextEncoder;var gw=112;function yw(r){let e=mw(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=Ne.decode(n.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(i.Name=n.Name),n.Tsize!==void 0&&(i.Tsize=n.Tsize),i})),t}var bw=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===I.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===I.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[I.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let s=0;s32?Rl(n):n)}[I.array.major](e,t){this.prefix(e),this.inRecursive.push({type:I.array,elements:0}),e.push([91])}[I.map.major](e,t){this.prefix(e),this.inRecursive.push({type:I.map,elements:0}),e.push([123])}[I.tag.major](e,t){}[I.float.major](e,t){if(t.type.name==="break"){let o=this.inRecursive.pop();if(o){if(o.type===I.array)e.push([93]);else if(o.type===I.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${wc} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],s=!1;for(let o=0;o=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos{for(;!this.done();){let c=this.ch();if(a.includes(c))this.pos++;else break}};if(this.ch()===45&&(t=!0,this.pos++),this.ch()===48)if(this.pos++,this.ch()===46)this.pos++,n=!0;else return new W(I.uint,0,this.pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`${ce} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${ce} unexpected token at position ${this.pos}`);n=!0,this.pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,i([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),o=parseFloat(s);return n?new W(I.float,o,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(o)?new W(o>=0?I.uint:I.negint,o,this.pos-e):new W(o>=0?I.uint:I.negint,BigInt(s),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${ce} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let s=this.pos,o=0;s=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,s));return this.pos=s+1,new W(I.string,c,o)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${ce} unexpected end of unicode escape sequence at position ${this.pos}`);let s=0;for(let o=0;o<4;o++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${ce} unexpected unicode escape character at position ${this.pos}`);s=s*16+a,this.pos++}return s},i=()=>{let s=this.ch(),o=null,a=s>239?4:s>223?3:s>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${ce} unexpected unicode sequence at position ${this.pos}`);let c,u,l,f;switch(a){case 1:s<128&&(o=s);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(f=(s&31)<<6|c&63,f>127&&(o=f));break;case 3:c=this.data[this.pos+1],u=this.data[this.pos+2],(c&192)===128&&(u&192)===128&&(f=(s&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:c=this.data[this.pos+1],u=this.data[this.pos+2],l=this.data[this.pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(o=f))}o===null?(o=65533,a=1):o>65535&&(o-=65536,t.push(o>>>10&1023|55296),o=56320|o&1023),t.push(o),this.pos+=a};for(;!this.done();){let s=this.ch(),o;switch(s){case 92:if(this.pos++,this.done())throw new Error(`${ce} unexpected string termination at position ${this.pos}`);switch(o=this.ch(),this.pos++,o){case 34:case 39:case 92:case 47:t.push(o);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${ce} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new W(I.string,Fm(t),this.pos-e);default:if(s<32)throw new Error(`${ce} invalid control character at position ${this.pos}`);s<128?(t.push(s),this.pos++):i()}}throw new Error(`${ce} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new W(I.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new W(I.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new W(I.null,null,4);case 102:return this.expect([102,97,108,115,101]),new W(I.false,!1,5);case 116:return this.expect([116,114,117,101]),new W(I.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${ce} unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this.pos++,this.skipWhitespace(),new W(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${ce} unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this.pos++,this.skipWhitespace(),new W(I.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new W(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${ce} unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this.pos++,this.skipWhitespace(),new W(I.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${ce} unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${ce} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function Jm(r,e){return e=Object.assign({tokenizer:new _c(r,e)},e),ws(r,e)}var ww={codec:gw,async*walk(r){yield*yw(r).Links.map(t=>t.Hash)}},Ew={codec:Kh,async*walk(){}},xw=42,vw={codec:113,async*walk(r){let e=[],t=[];t[xw]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=Ne.decode(n.subarray(1));return e.push(i),i},ws(r,{tags:t}),yield*e}},e3=class extends _c{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===I.map){let t=this._next();if(t.type===I.string&&t.value==="/"){let n=this._next();if(n.type===I.string){if(this._next().type!==I.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new W(I.tag,42,0)}if(n.type===I.map){let i=this._next();if(i.type===I.string&&i.value==="bytes"){let s=this._next();if(s.type===I.string){for(let a=0;a<2;a++)if(this._next().type!==I.break)throw new Error("Invalid encoded Bytes form");let o=fs.decode(`m${s.value}`);return new W(I.bytes,o,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},_w={codec:297,async*walk(r){let e=[],t=[];t[xw]=n=>{let i=Ne.parse(n);return e.push(i),i},Jm(r,{tags:t,tokenizer:new e3(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var bM=[Ew,ww,vw,_w],Aw="/pin/",Sw="/pinned-block/",t3=yl,Rw=1;function Iw(r){return r.version===0&&(r=r.toV1()),new pt(`${Aw}${r.toString(t3)}`)}var F0=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers={},[...bM,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=Iw(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let s=new kt({concurrency:Rw});s.add(async()=>{await this.#e(e,s,c=>{c.pinnedBy.find(u=>fe(u,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let o=Le();s.on("error",c=>{s.clear(),o.reject(c)}),await Promise.race([s.onIdle(),o.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,A0(a),t),{cid:e,...a}}async#e(e,t,n,i){if(i.depth===-1)return;let s=this.dagWalkers[e.code];if(s==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let o=await this.blockstore.get(e,i);await this.#t(e,n,i);for await(let a of s.walk(o))t.add(async()=>{await this.#e(a,t,n,{...i,depth:i.depth-1})})}async#t(e,t,n){let i=new pt(`${Sw}${t3.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=ws(await this.datastore.get(i,n))}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(t(s),s.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,A0(s),n),n.onProgress?.(new Qe("helia:pin:add",{detail:e}))}async rm(e,t={}){let n=Iw(e),i=await this.datastore.get(n,t),s=ws(i);await this.datastore.delete(n,t);let o=new kt({concurrency:Rw});return o.add(async()=>{await this.#e(e,o,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>fe(c,e.bytes))},{...t,depth:s.depth})}),await o.onIdle(),{cid:e,...s}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Aw+(e.cid!=null?`${e.cid.toString(yl)}`:"")},e)){let i=Ne.parse(t.toString().substring(5),yl),s=ws(n);yield{cid:i,...s}}}async isPinned(e,t={}){let n=new pt(`${Sw}${t3.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var r3=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},n3=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Tw=r=>globalThis.DOMException===void 0?new n3(r):new DOMException(r),Dw=r=>{let e=r.reason===void 0?Tw("This operation was aborted."):r.reason;return e instanceof Error?e:Tw(e)};function i3(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(Dw(h)),h.addEventListener("abort",()=>{l(Dw(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new r3;o=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},c}var Cw=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var s3="lock:worker:request-read",o3="lock:worker:release-read",a3="lock:master:grant-read",c3="lock:worker:request-write",u3="lock:worker:release-write",l3="lock:master:grant-write";var no={},Sc=r=>{r.addEventListener("message",e=>{Sc.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Sc.dispatchEvent("message",r,e)})};Sc.addEventListener=(r,e)=>{no[r]==null&&(no[r]=[]),no[r].push(e)};Sc.removeEventListener=(r,e)=>{no[r]!=null&&(no[r]=no[r].filter(t=>t===e))};Sc.dispatchEvent=function(r,e,t){no[r]!=null&&no[r].forEach(n=>n(e,t))};var f3=Sc;var Pw=(r,e,t,n,i)=>(s,o)=>{if(o.data.type!==t)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)}))}}))},kw=(r,e,t,n)=>async()=>{let i=Cw();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",o)})},wM={singleProcess:!1},Nw=r=>{if(r=Object.assign({},wM,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return f3.addEventListener("message",Pw(t,"requestReadLock",s3,o3,a3)),f3.addEventListener("message",Pw(t,"requestWriteLock",c3,u3,l3)),t}return{isWorker:!0,readLock:t=>kw(t,s3,a3,o3),writeLock:t=>kw(t,c3,l3,u3)}};var pa={},io;async function h3(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await i3((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var EM=(r,e)=>{if(io.isWorker===!0)return{readLock:io.readLock(r,e),writeLock:io.writeLock(r,e)};let t=new kt({concurrency:1}),n;return{async readLock(){if(n!=null)return await h3(n,e);n=new kt({concurrency:e.concurrency,autoStart:!1});let i=n,s=h3(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await h3(t,e)}}},xM={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Kl(r){let e=Object.assign({},xM,r);return io==null&&(io=Nw(e),io.isWorker!==!0&&(io.addEventListener("requestReadLock",t=>{pa[t.data.name]!=null&&pa[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),io.addEventListener("requestWriteLock",async t=>{pa[t.data.name]!=null&&pa[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),pa[e.name]==null&&(pa[e.name]=EM(e.name,e)),pa[e.name]}var K0=class{lock;child;pins;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Kl({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await i.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}};var d3=new pt("/version"),Ow=1;async function Bw(r){if(!await r.has(d3)){await r.put(d3,G(`${Ow}`));return}let e=await r.get(d3),t=U(e);if(parseInt(t,10)!==Ow)throw new Error("Unknown datastore version, a datastore migration may be required")}var V0=class{child;bitswap;constructor(e,t={}){this.child=e,this.bitswap=t.bitswap}unwrap(){return this.child}async put(e,t,n={}){return await this.child.has(e)?(n.onProgress?.(new Qe("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new Qe("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new Qe("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Lr(e,async({cid:s})=>{let o=await this.child.has(s);return o&&t.onProgress?.(new Qe("blocks:put-many:duplicate",s)),!o}),i=ia(n,({cid:s,block:o})=>{t.onProgress?.(new Qe("blocks:put-many:bitswap:notify",s)),this.bitswap?.notify(s,o,t)});t.onProgress?.(new Qe("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async get(e,t={}){if(t.offline!==!0&&this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new Qe("blocks:get:bitswap:get",e));let n=await this.bitswap.want(e,t);return t.onProgress?.(new Qe("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),n}return t.onProgress?.(new Qe("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new Qe("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ia(e,async n=>{if(t.offline!==!0&&this.bitswap?.isStarted()===!0&&!await this.child.has(n)){t.onProgress?.(new Qe("blocks:get-many:bitswap:get",n));let i=await this.bitswap.want(n,t);t.onProgress?.(new Qe("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t)}}))}async delete(e,t={}){t.onProgress?.(new Qe("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new Qe("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new Qe("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};var p3=C("helia"),q0=class{libp2p;blockstore;datastore;pins;#e;constructor(e){let t=[Ke,em,Fi,...e.hashers??[]];this.#e=j9(e.libp2p,e.blockstore,{hashLoader:{getHasher:async i=>{let s=t.find(o=>o.code===i||o.name===i);if(s!=null)return s;throw new Error(`Could not load hasher for code/name "${i}"`)}}});let n=new V0(e.blockstore,{bitswap:this.#e});this.pins=new F0(e.datastore,n,e.dagWalkers??[]),this.libp2p=e.libp2p,this.blockstore=new K0(n,this.pins,{holdGcLock:e.holdGcLock}),this.datastore=e.datastore}async start(){await Bw(this.datastore),await this.#e?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await this.#e?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();p3("gc start"),await Wr(i.deleteMany(async function*(){for await(let{cid:s}of i.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new Qe("helia:gc:deleted",s))}catch(o){p3.error("Error during gc",o),e.onProgress?.(new Qe("helia:gc:error",o))}}()))}finally{t()}p3("gc finished")}};var PS=j(Xr(),1);var Rd={};be(Rd,{generateEphemeralKeyPair:()=>Ax,generateKeyPair:()=>of,generateKeyPairFromSeed:()=>kV,importKey:()=>Vc,keyStretcher:()=>Nx,keysPBM:()=>Lc,marshalPrivateKey:()=>w4,marshalPublicKey:()=>af,supportedKeys:()=>ji,unmarshalPrivateKey:()=>_i,unmarshalPublicKey:()=>vi});var nle=j(ma(),1),ile=j(M3(),1);var Sd=j(Ve(),1);var i4={};be(i4,{Ed25519PrivateKey:()=>Sa,Ed25519PublicKey:()=>Zl,generateKeyPair:()=>eV,generateKeyPairFromSeed:()=>n4,unmarshalEd25519PrivateKey:()=>ZK,unmarshalEd25519PublicKey:()=>JK});function U3(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function GF(r){if(typeof r!="boolean")throw new Error(`Expected boolean, not ${r}`)}function XE(r,...e){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function WF(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");U3(r.outputLen),U3(r.blockLen)}function YF(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function QF(r,e){XE(r);let t=e.outputLen;if(r.lengthr instanceof Uint8Array;var od=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),mi=(r,e)=>r<<32-e|r>>>e,jF=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!jF)throw new Error("Non little-endian hardware is not supported");var gae=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function F3(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function uo(r){if(typeof r=="string"&&(r=F3(r)),!jE(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function ad(...r){let e=new Uint8Array(r.reduce((n,i)=>n+i.length,0)),t=0;return r.forEach(n=>{if(!jE(n))throw new Error("Uint8Array expected");e.set(n,t),t+=n.length}),e}var Cc=class{clone(){return this._cloneInto()}};function lo(r){let e=n=>r().update(uo(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function fo(r=32){if(sd&&typeof sd.getRandomValues=="function")return sd.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function ZF(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+u,a,n)}var Pc=class extends Cc{constructor(e,t,n,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=od(this.buffer)}update(e){dn.exists(this);let{view:t,buffer:n,blockLen:i}=this;e=uo(e);let s=e.length;for(let o=0;oi-o&&(this.process(n,0),o=0);for(let f=o;fl.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>K3&cd)}:{h:Number(r>>K3&cd)|0,l:Number(r&cd)|0}}function JF(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;iBigInt(r>>>0)<>>0),tK=(r,e,t)=>r>>>t,rK=(r,e,t)=>r<<32-t|e>>>t,nK=(r,e,t)=>r>>>t|e<<32-t,iK=(r,e,t)=>r<<32-t|e>>>t,sK=(r,e,t)=>r<<64-t|e>>>t-32,oK=(r,e,t)=>r>>>t-32|e<<64-t,aK=(r,e)=>e,cK=(r,e)=>r,uK=(r,e,t)=>r<>>32-t,lK=(r,e,t)=>e<>>32-t,fK=(r,e,t)=>e<>>64-t,hK=(r,e,t)=>r<>>64-t;function dK(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}var pK=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),mK=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,gK=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),yK=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,bK=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),wK=(r,e,t,n,i,s)=>e+t+n+i+s+(r/2**32|0)|0,EK={fromBig:ZE,split:JF,toBig:eK,shrSH:tK,shrSL:rK,rotrSH:nK,rotrSL:iK,rotrBH:sK,rotrBL:oK,rotr32H:aK,rotr32L:cK,rotlSH:uK,rotlSL:lK,rotlBH:fK,rotlBL:hK,add:dK,add3L:pK,add3H:mK,add4L:gK,add4H:yK,add5H:wK,add5L:bK},ke=EK;var[xK,vK]=ke.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),ho=new Uint32Array(80),po=new Uint32Array(80),kc=class extends Pc{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,i,s,o,a,c,u,l,f,h,d,p,m,g]}set(e,t,n,i,s,o,a,c,u,l,f,h,d,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let E=0;E<16;E++,t+=4)ho[E]=e.getUint32(t),po[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=ho[E-15]|0,x=po[E-15]|0,v=ke.rotrSH(_,x,1)^ke.rotrSH(_,x,8)^ke.shrSH(_,x,7),R=ke.rotrSL(_,x,1)^ke.rotrSL(_,x,8)^ke.shrSL(_,x,7),T=ho[E-2]|0,P=po[E-2]|0,q=ke.rotrSH(T,P,19)^ke.rotrBH(T,P,61)^ke.shrSH(T,P,6),$=ke.rotrSL(T,P,19)^ke.rotrBL(T,P,61)^ke.shrSL(T,P,6),Q=ke.add4L(R,$,po[E-7],po[E-16]),te=ke.add4H(Q,v,q,ho[E-7],ho[E-16]);ho[E]=te|0,po[E]=Q|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let E=0;E<80;E++){let _=ke.rotrSH(f,h,14)^ke.rotrSH(f,h,18)^ke.rotrBH(f,h,41),x=ke.rotrSL(f,h,14)^ke.rotrSL(f,h,18)^ke.rotrBL(f,h,41),v=f&d^~f&m,R=h&p^~h&g,T=ke.add5L(b,x,R,vK[E],po[E]),P=ke.add5H(T,y,_,v,xK[E],ho[E]),q=T|0,$=ke.rotrSH(n,i,28)^ke.rotrBH(n,i,34)^ke.rotrBH(n,i,39),Q=ke.rotrSL(n,i,28)^ke.rotrBL(n,i,34)^ke.rotrBL(n,i,39),te=n&s^n&a^s&a,_e=i&o^i&c^o&c;y=m|0,b=g|0,m=d|0,g=p|0,d=f|0,p=h|0,{h:f,l:h}=ke.add(u|0,l|0,P|0,q|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;let k=ke.add3L(q,Q,_e);n=ke.add3H(k,P,$,te),i=k|0}({h:n,l:i}=ke.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=ke.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ke.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ke.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=ke.add(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=ke.add(this.Fh|0,this.Fl|0,d|0,p|0),{h:m,l:g}=ke.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=ke.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,i,s,o,a,c,u,l,f,h,d,p,m,g,y,b)}roundClean(){ho.fill(0),po.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)}},V3=class extends kc{constructor(){super(),this.Ah=-1942145080,this.Al=424955298,this.Bh=1944164710,this.Bl=-1982016298,this.Ch=502970286,this.Cl=855612546,this.Dh=1738396948,this.Dl=1479516111,this.Eh=258812777,this.El=2077511080,this.Fh=2011393907,this.Fl=79989058,this.Gh=1067287976,this.Gl=1780299464,this.Hh=286451373,this.Hl=-1848208735,this.outputLen=28}},q3=class extends kc{constructor(){super(),this.Ah=573645204,this.Al=-64227540,this.Bh=-1621794909,this.Bl=-934517566,this.Ch=596883563,this.Cl=1867755857,this.Dh=-1774684391,this.Dl=1497426621,this.Eh=-1775747358,this.El=-1467023389,this.Fh=-1101128155,this.Fl=1401305490,this.Gh=721525244,this.Gl=746961066,this.Hh=246885852,this.Hl=-2117784414,this.outputLen=32}},z3=class extends kc{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}},$3=lo(()=>new kc),Rae=lo(()=>new V3),Iae=lo(()=>new q3),Aae=lo(()=>new z3);var fd={};be(fd,{bitGet:()=>AK,bitLen:()=>IK,bitMask:()=>Wl,bitSet:()=>TK,bytesToHex:()=>Xi,bytesToNumberBE:()=>gi,bytesToNumberLE:()=>qn,concatBytes:()=>yi,createHmacDrbg:()=>W3,ensureBytes:()=>ot,equalBytes:()=>rx,hexToBytes:()=>va,hexToNumber:()=>G3,numberToBytesBE:()=>Ss,numberToBytesLE:()=>Rs,numberToHexUnpadded:()=>tx,numberToVarBytesBE:()=>RK,utf8ToBytes:()=>nx,validateObject:()=>pn});var ex=BigInt(0),ud=BigInt(1),_K=BigInt(2),ld=r=>r instanceof Uint8Array,SK=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Xi(r){if(!ld(r))throw new Error("Uint8Array expected");let e="";for(let t=0;tn+i.length,0)),t=0;return r.forEach(n=>{if(!ld(n))throw new Error("Uint8Array expected");e.set(n,t),t+=n.length}),e}function rx(r,e){if(r.length!==e.length)return!1;for(let t=0;tex;r>>=ud,e+=1);return e}function AK(r,e){return r>>BigInt(e)&ud}var TK=(r,e,t)=>r|(t?ud:ex)<(_K<new Uint8Array(r),JE=r=>Uint8Array.from(r);function W3(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=H3(r),i=H3(r),s=0,o=()=>{n.fill(1),i.fill(0),s=0},a=(...f)=>t(i,n,...f),c=(f=H3())=>{i=a(JE([0]),f),n=a(),f.length!==0&&(i=a(JE([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f{o(),c(f);let d;for(;!(d=h(u()));)c();return o(),d}}var DK={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function pn(r,e,t={}){let n=(i,s,o)=>{let a=DK[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[i];if(!(o&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${s}`)};for(let[i,s]of Object.entries(e))n(i,s,!1);for(let[i,s]of Object.entries(t))n(i,s,!0);return r}var tr=BigInt(0),_t=BigInt(1),_a=BigInt(2),CK=BigInt(3),Y3=BigInt(4),ix=BigInt(5),sx=BigInt(8),PK=BigInt(9),kK=BigInt(16);function je(r,e){let t=r%e;return t>=tr?t:e+t}function Q3(r,e,t){if(t<=tr||e 0");if(t===_t)return tr;let n=_t;for(;e>tr;)e&_t&&(n=n*r%t),r=r*r%t,e>>=_t;return n}function gt(r,e,t){let n=r;for(;e-- >tr;)n*=n,n%=t;return n}function hd(r,e){if(r===tr||e<=tr)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=je(r,e),n=e,i=tr,s=_t,o=_t,a=tr;for(;t!==tr;){let u=n/t,l=n%t,f=i-o*u,h=s-a*u;n=t,t=l,i=o,s=a,o=f,a=h}if(n!==_t)throw new Error("invert: does not exist");return je(i,e)}function NK(r){let e=(r-_t)/_a,t,n,i;for(t=r-_t,n=0;t%_a===tr;t/=_a,n++);for(i=_a;i(je(r,e)&_t)===_t,BK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function X3(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=BK.reduce((n,i)=>(n[i]="function",n),e);return pn(r,t)}function LK(r,e,t){if(t 0");if(t===tr)return r.ONE;if(t===_t)return e;let n=r.ONE,i=e;for(;t>tr;)t&_t&&(n=r.mul(n,i)),i=r.sqr(i),t>>=_t;return n}function MK(r,e){let t=new Array(e.length),n=e.reduce((s,o,a)=>r.is0(o)?s:(t[a]=s,r.mul(s,o)),r.ONE),i=r.inv(n);return e.reduceRight((s,o,a)=>r.is0(o)?s:(t[a]=r.mul(s,t[a]),r.mul(s,o)),i),t}function dd(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function pd(r,e,t=!1,n={}){if(r<=tr)throw new Error(`Expected Fp ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:s}=dd(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=OK(r),a=Object.freeze({ORDER:r,BITS:i,BYTES:s,MASK:Wl(i),ZERO:tr,ONE:_t,create:c=>je(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return tr<=c&&cc===tr,isOdd:c=>(c&_t)===_t,neg:c=>je(-c,r),eql:(c,u)=>c===u,sqr:c=>je(c*c,r),add:(c,u)=>je(c+u,r),sub:(c,u)=>je(c-u,r),mul:(c,u)=>je(c*u,r),pow:(c,u)=>LK(a,c,u),div:(c,u)=>je(c*hd(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>hd(c,r),sqrt:n.sqrt||(c=>o(a,c)),invertBatch:c=>MK(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>t?Rs(c,s):Ss(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?qn(c):gi(c)}});return Object.freeze(a)}function ax(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function cx(r,e,t=!1){r=ot("privateHash",r);let n=r.length,i=dd(e).nByteLength+8;if(i<24||n1024)throw new Error(`hashToPrivateScalar: expected ${i}-1024 bytes of input, got ${n}`);let s=t?qn(r):gi(r);return je(s,e-_t)+_t}var FK=BigInt(0),j3=BigInt(1);function md(r,e){let t=(i,s)=>{let o=s.negate();return i?o:s},n=i=>{let s=Math.ceil(e/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:t,unsafeLadder(i,s){let o=r.ZERO,a=i;for(;s>FK;)s&j3&&(o=o.add(a)),a=a.double(),s>>=j3;return o},precomputeWindow(i,s){let{windows:o,windowSize:a}=n(s),c=[],u=i,l=u;for(let f=0;f>=d,g>c&&(g-=h,o+=j3);let y=m,b=m+Math.abs(g)-1,E=p%2!==0,_=g<0;g===0?l=l.add(t(E,s[y])):u=u.add(t(_,s[b]))}return{p:u,f:l}},wNAFCached(i,s,o,a){let c=i._WINDOW_SIZE||1,u=s.get(i);return u||(u=this.precomputeWindow(i,c),c!==1&&s.set(i,a(u))),this.wNAF(c,u,o)}}}function Yl(r){return X3(r.Fp),pn(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...dd(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var bi=BigInt(0),mn=BigInt(1),gd=BigInt(2),KK=BigInt(8),VK={zip215:!0};function qK(r){let e=Yl(r);return pn(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function yd(r){let e=qK(r),{Fp:t,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=gd<{try{return{isValid:!0,value:t.sqrt(M*t.inv(A))}}catch{return{isValid:!1,value:bi}}}),h=e.adjustScalarBytes||(M=>M),d=e.domain||((M,A,H)=>{if(A.length||H)throw new Error("Contexts/pre-hash are not supported");return M}),p=M=>typeof M=="bigint"&&bip(M)&&p(A)&&MM===bi||m(M,u);function y(M,A){if(m(M,A))return M;throw new Error(`Expected valid scalar < ${A}, got ${typeof M} ${M}`)}function b(M){return M===bi?M:y(M,n)}let E=new Map;function _(M){if(!(M instanceof x))throw new Error("ExtendedPoint expected")}class x{constructor(A,H,X,re){if(this.ex=A,this.ey=H,this.ez=X,this.et=re,!g(A))throw new Error("x required");if(!g(H))throw new Error("y required");if(!g(X))throw new Error("z required");if(!g(re))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof x)throw new Error("extended point not allowed");let{x:H,y:X}=A||{};if(!g(H)||!g(X))throw new Error("invalid affine point");return new x(H,X,mn,l(H*X))}static normalizeZ(A){let H=t.invertBatch(A.map(X=>X.ez));return A.map((X,re)=>X.toAffine(H[re])).map(x.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,E.delete(this)}assertValidity(){let{a:A,d:H}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:X,ey:re,ez:xe,et:Se}=this,Be=l(X*X),Ae=l(re*re),Ce=l(xe*xe),lt=l(Ce*Ce),it=l(Be*A),pr=l(Ce*l(it+Ae)),mr=l(lt+l(H*l(Be*Ae)));if(pr!==mr)throw new Error("bad point: equation left != right (1)");let jt=l(X*re),Tr=l(xe*Se);if(jt!==Tr)throw new Error("bad point: equation left != right (2)")}equals(A){_(A);let{ex:H,ey:X,ez:re}=this,{ex:xe,ey:Se,ez:Be}=A,Ae=l(H*Be),Ce=l(xe*re),lt=l(X*Be),it=l(Se*re);return Ae===Ce&<===it}is0(){return this.equals(x.ZERO)}negate(){return new x(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:A}=e,{ex:H,ey:X,ez:re}=this,xe=l(H*H),Se=l(X*X),Be=l(gd*l(re*re)),Ae=l(A*xe),Ce=H+X,lt=l(l(Ce*Ce)-xe-Se),it=Ae+Se,pr=it-Be,mr=Ae-Se,jt=l(lt*pr),Tr=l(it*mr),us=l(lt*mr),Jo=l(pr*it);return new x(jt,Tr,Jo,us)}add(A){_(A);let{a:H,d:X}=e,{ex:re,ey:xe,ez:Se,et:Be}=this,{ex:Ae,ey:Ce,ez:lt,et:it}=A;if(H===BigInt(-1)){let f6=l((xe-re)*(Ce+Ae)),h6=l((xe+re)*(Ce-Ae)),C2=l(h6-f6);if(C2===bi)return this.double();let d6=l(Se*gd*it),p6=l(Be*gd*lt),m6=p6+d6,g6=h6+f6,y6=p6-d6,RN=l(m6*C2),IN=l(g6*y6),AN=l(m6*y6),TN=l(C2*g6);return new x(RN,IN,TN,AN)}let pr=l(re*Ae),mr=l(xe*Ce),jt=l(Be*X*it),Tr=l(Se*lt),us=l((re+xe)*(Ae+Ce)-pr-mr),Jo=Tr-jt,ll=Tr+jt,l6=l(mr-H*pr),xN=l(us*Jo),vN=l(ll*l6),_N=l(us*l6),SN=l(Jo*ll);return new x(xN,vN,SN,_N)}subtract(A){return this.add(A.negate())}wNAF(A){return T.wNAFCached(this,E,A,x.normalizeZ)}multiply(A){let{p:H,f:X}=this.wNAF(y(A,n));return x.normalizeZ([H,X])[0]}multiplyUnsafe(A){let H=b(A);return H===bi?R:this.equals(R)||H===mn?this:this.equals(v)?this.wNAF(H).p:T.unsafeLadder(this,H)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(A){let{ex:H,ey:X,ez:re}=this,xe=this.is0();A==null&&(A=xe?KK:t.inv(re));let Se=l(H*A),Be=l(X*A),Ae=l(re*A);if(xe)return{x:bi,y:mn};if(Ae!==mn)throw new Error("invZ was invalid");return{x:Se,y:Be}}clearCofactor(){let{h:A}=e;return A===mn?this:this.multiplyUnsafe(A)}static fromHex(A,H=!1){let{d:X,a:re}=e,xe=t.BYTES;A=ot("pointHex",A,xe);let Se=A.slice(),Be=A[xe-1];Se[xe-1]=Be&-129;let Ae=qn(Se);Ae===bi||(H?y(Ae,u):y(Ae,t.ORDER));let Ce=l(Ae*Ae),lt=l(Ce-mn),it=l(X*Ce-re),{isValid:pr,value:mr}=f(lt,it);if(!pr)throw new Error("Point.fromHex: invalid y coordinate");let jt=(mr&mn)===mn,Tr=(Be&128)!==0;if(!H&&mr===bi&&Tr)throw new Error("Point.fromHex: x=0 and x_0=1");return Tr!==jt&&(mr=l(-mr)),x.fromAffine({x:mr,y:Ae})}static fromPrivateKey(A){return $(A).point}toRawBytes(){let{x:A,y:H}=this.toAffine(),X=Rs(H,t.BYTES);return X[X.length-1]|=A&mn?128:0,X}toHex(){return Xi(this.toRawBytes())}}x.BASE=new x(e.Gx,e.Gy,mn,l(e.Gx*e.Gy)),x.ZERO=new x(bi,mn,mn,bi);let{BASE:v,ZERO:R}=x,T=md(x,a*8);function P(M){return je(M,n)}function q(M){return P(qn(M))}function $(M){let A=a;M=ot("private key",M,A);let H=ot("hashed private key",s(M),2*A),X=h(H.slice(0,A)),re=H.slice(A,2*A),xe=q(X),Se=v.multiply(xe),Be=Se.toRawBytes();return{head:X,prefix:re,scalar:xe,point:Se,pointBytes:Be}}function Q(M){return $(M).pointBytes}function te(M=new Uint8Array,...A){let H=yi(...A);return q(s(d(H,ot("context",M),!!i)))}function _e(M,A,H={}){M=ot("message",M),i&&(M=i(M));let{prefix:X,scalar:re,pointBytes:xe}=$(A),Se=te(H.context,X,M),Be=v.multiply(Se).toRawBytes(),Ae=te(H.context,Be,xe,M),Ce=P(Se+Ae*re);b(Ce);let lt=yi(Be,Rs(Ce,t.BYTES));return ot("result",lt,a*2)}let k=VK;function F(M,A,H,X=k){let{context:re,zip215:xe}=X,Se=t.BYTES;M=ot("signature",M,2*Se),A=ot("message",A),i&&(A=i(A));let Be=qn(M.slice(Se,2*Se)),Ae,Ce,lt;try{Ae=x.fromHex(H,xe),Ce=x.fromHex(M.slice(0,Se),xe),lt=v.multiplyUnsafe(Be)}catch{return!1}if(!xe&&Ae.isSmallOrder())return!1;let it=te(re,Ce.toRawBytes(),Ae.toRawBytes(),A);return Ce.add(Ae.multiplyUnsafe(it)).subtract(lt).clearCofactor().equals(x.ZERO)}return v._setWindowSize(8),{CURVE:e,getPublicKey:Q,sign:_e,verify:F,ExtendedPoint:x,utils:{getExtendedPublicKey:$,randomPrivateKey:()=>o(t.BYTES),precompute(M=8,A=x.BASE){return A._setWindowSize(M),A.multiply(BigInt(3)),A}}}}var Ql=BigInt(0),Z3=BigInt(1);function zK(r){return pn(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function ux(r){let e=zK(r),{P:t}=e,n=E=>je(E,t),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>Q3(E,t-BigInt(2),t));function u(E,_,x){let v=n(E*(_-x));return _=n(_-v),x=n(x+v),[_,x]}function l(E){if(typeof E=="bigint"&&Ql<=E&&E=Ql;k--){let F=v>>k&Z3;Q^=F,te=u(Q,T,q),T=te[0],q=te[1],te=u(Q,P,$),P=te[0],$=te[1],Q=F;let O=T+P,M=n(O*O),A=T-P,H=n(A*A),X=M-H,re=q+$,xe=q-$,Se=n(xe*O),Be=n(re*A),Ae=Se+Be,Ce=Se-Be;q=n(Ae*Ae),$=n(R*n(Ce*Ce)),T=n(M*H),P=n(X*(M+n(f*X)))}te=u(Q,T,q),T=te[0],q=te[1],te=u(Q,P,$),P=te[0],$=te[1];let _e=c(P);return n(T*_e)}function d(E){return Rs(n(E),s)}function p(E){let _=ot("u coordinate",E,s);return o===s&&(_[o-1]&=127),qn(_)}function m(E){let _=ot("scalar",E);if(_.length!==s&&_.length!==o)throw new Error(`Expected ${s} or ${o} bytes, got ${_.length}`);return qn(a(_))}function g(E,_){let x=p(_),v=m(E),R=h(x,v);if(R===Ql)throw new Error("Invalid private or public key received");return d(R)}let y=d(e.Gu);function b(E){return g(E,y)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(E,_)=>g(E,_),getPublicKey:E=>b(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}var Xl=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),lx=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),jae=BigInt(0),HK=BigInt(1),J3=BigInt(2),GK=BigInt(5),fx=BigInt(10),WK=BigInt(20),YK=BigInt(40),hx=BigInt(80);function dx(r){let e=Xl,n=r*r%e*r%e,i=gt(n,J3,e)*n%e,s=gt(i,HK,e)*r%e,o=gt(s,GK,e)*s%e,a=gt(o,fx,e)*o%e,c=gt(a,WK,e)*a%e,u=gt(c,YK,e)*c%e,l=gt(u,hx,e)*u%e,f=gt(l,hx,e)*u%e,h=gt(f,fx,e)*o%e;return{pow_p_5_8:gt(h,J3,e)*r%e,b2:n}}function px(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function QK(r,e){let t=Xl,n=je(e*e*e,t),i=je(n*n*e,t),s=dx(r*i).pow_p_5_8,o=je(r*n*s,t),a=je(e*o*o,t),c=o,u=je(o*lx,t),l=a===r,f=a===je(-r,t),h=a===je(-r*lx,t);return l&&(o=c),(f||h)&&(o=u),ox(o,t)&&(o=je(-o,t)),{isValid:l||f,value:o}}var Is=pd(Xl,void 0,!0),e4={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Is,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:$3,randomBytes:fo,adjustScalarBytes:px,uvRatio:QK},Nc=yd(e4);function mx(r,e,t){if(e.length>255)throw new Error("Context is too big");return ad(F3("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var Zae=yd({...e4,domain:mx}),Jae=yd({...e4,domain:mx,prehash:$3}),jl=(()=>ux({P:Xl,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=Xl,{pow_p_5_8:t,b2:n}=dx(r);return je(gt(t,BigInt(3),e)*n,e)},adjustScalarBytes:px,randomBytes:fo}))();var XK=(Is.ORDER+BigInt(3))/BigInt(8),ece=Is.pow(J3,XK),tce=Is.sqrt(Is.neg(Is.ONE)),rce=(Is.ORDER-BigInt(5))/BigInt(8),nce=BigInt(486662);var ice=ax(Is,Is.neg(BigInt(486664)));var sce=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),oce=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ace=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),cce=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var uce=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Oc=32,As=64,bd=32;async function gx(){let r=Nc.utils.randomPrivateKey(),e=Nc.getPublicKey(r);return{privateKey:Ex(r,e),publicKey:e}}async function yx(r){if(r.length!==bd)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=Nc.getPublicKey(e);return{privateKey:Ex(e,t),publicKey:t}}async function bx(r,e){let t=r.subarray(0,bd);return Nc.sign(e,t)}async function wx(r,e,t){return Nc.verify(e,t,r)}function Ex(r,e){let t=new Uint8Array(As);for(let n=0;nyt,PrivateKey:()=>Ei,PublicKey:()=>wi});var yt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(yt||(yt={}));var r4;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(r4||(r4={}));(function(r){r.codec=()=>ft(r4)})(yt||(yt={}));var wi;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),yt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=yt.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(wi||(wi={}));var Ei;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),yt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=yt.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(Ei||(Ei={}));var Zl=class{_key;constructor(e){this._key=Mc(e,Oc)}async verify(e,t){return wx(this._key,t,e)}marshal(){return this._key}get bytes(){return wi.encode({Type:yt.Ed25519,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ke.digest(this.bytes);return e}},Sa=class{_key;_publicKey;constructor(e,t){this._key=Mc(e,As),this._publicKey=Mc(t,Oc)}async sign(e){return bx(this._key,e)}get public(){return new Zl(this._publicKey)}marshal(){return this._key}get bytes(){return Ei.encode({Type:yt.Ed25519,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ke.digest(this.bytes);return e}async id(){let e=Fi.digest(this.public.bytes);return Re.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Bc(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function ZK(r){if(r.length>As){r=Mc(r,As+Oc);let n=r.subarray(0,As),i=r.subarray(As,r.length);return new Sa(n,i)}r=Mc(r,As);let e=r.subarray(0,As),t=r.subarray(Oc);return new Sa(e,t)}function JK(r){return r=Mc(r,Oc),new Zl(r)}async function eV(){let{privateKey:r,publicKey:e}=await gx();return new Sa(r,e)}async function n4(r){let{privateKey:e,publicKey:t}=await yx(r);return new Sa(e,t)}function Mc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new w(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var Rce=j(Nt(),1),Ice=j(Gl(),1),vx=j(Ve(),1);function xi(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=ve([new Uint8Array(e-t.length),t])}return U(t,"base64url")}function gn(r){let e=Ed(r);return new vx.default.jsbn.BigInteger(U(e,"base16"),16)}function Ed(r,e){let t=G(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=ve([new Uint8Array(e-t.length),t])}return t}var _x={"P-256":256,"P-384":384,"P-521":521},tV=Object.keys(_x),s4=tV.join(" / ");async function Sx(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${s4}`,"ERR_INVALID_CURVE");let e=await qt.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(s,o)=>{let a;o!=null?a=await qt.get().subtle.importKey("jwk",nV(r,o),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await qt.get().subtle.importKey("jwk",Ix(r,s),{name:"ECDH",namedCurve:r},!1,[]),u=await qt.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,_x[r]);return new Uint8Array(u,0,u.byteLength)},n=await qt.get().subtle.exportKey("jwk",e.publicKey);return{key:rV(n),genSharedKey:t}}var Rx={"P-256":32,"P-384":48,"P-521":66};function rV(r){if(r.crv==null||r.x==null||r.y==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new w(`Unknown curve: ${r.crv}. Must be ${s4}`,"ERR_INVALID_CURVE");let e=Rx[r.crv];return ve([Uint8Array.from([4]),Ed(r.x,e),Ed(r.y,e)],1+e*2)}function Ix(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${s4}`,"ERR_INVALID_CURVE");let t=Rx[r];if(!fe(e.subarray(0,1),Uint8Array.from([4])))throw new w("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:U(e.subarray(1,t+1),"base64url"),y:U(e.subarray(1+t),"base64url"),ext:!0}}var nV=(r,e)=>({...Ix(r,e.public),d:U(e.private,"base64url")});var Ax=Sx;async function Tx(r,e){let t=fs.decode(r);return wd().decrypt(t,e)}var Dx={SHA1:20,SHA256:32,SHA512:64};var iV={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},sV=async(r,e)=>{let t=await qt.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function Cx(r,e){let t=iV[r],n=await qt.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(i){return sV(n,i)},length:Dx[r]}}var kx={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function Nx(r,e,t){let n=kx[r];if(n==null){let b=Object.keys(kx).join(" / ");throw new w(`unknown cipher type '${r}'. Must be ${b}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new w("missing hash type","ERR_MISSING_HASH_TYPE");let i=n.keySize,s=n.ivSize,o=20,a=G("key expansion"),c=2*(s+i+o),u=await Cx(e,t),l=await u.digest(a),f=[],h=0;for(;hc&&(E=c-h),f.push(b),h+=E,l=await u.digest(l)}let d=c/2,p=ve(f),m=p.subarray(0,d),g=p.subarray(d,c),y=b=>({iv:b.subarray(0,s),cipherKey:b.subarray(s,s+i),macKey:b.subarray(s+i)});return{k1:y(m),k2:y(g)}}var f4={};be(f4,{MAX_KEY_SIZE:()=>rf,RsaPrivateKey:()=>Uc,RsaPublicKey:()=>tf,fromJwk:()=>mV,generateKeyPair:()=>gV,unmarshalRsaPrivateKey:()=>dV,unmarshalRsaPublicKey:()=>pV});var ef=j(Ve(),1);var yue=j(c4(),1);function zn(r){if(isNaN(r)||r<=0)throw new w("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return fo(r)}var Jce=j(Dc(),1),u4=j(Ve(),1);function Ux(r,e){return e.map(t=>gn(r[t]))}function Fx(r){return u4.default.pki.setRsaPrivateKey(...Ux(r,["n","e","d","p","q","dp","dq","qi"]))}function Kx(r){return u4.default.pki.setRsaPublicKey(...Ux(r,["n","e"]))}var Ia={};be(Ia,{jwkToPkcs1:()=>cV,jwkToPkix:()=>lV,pkcs1ToJwk:()=>aV,pkixToJwk:()=>uV});var rue=j(ma(),1),nue=j(Dc(),1);var Ts=j(Ve(),1);function aV(r){let e=Ts.default.asn1.fromDer(U(r,"ascii")),t=Ts.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:xi(t.n),e:xi(t.e),d:xi(t.d),p:xi(t.p),q:xi(t.q),dp:xi(t.dP),dq:xi(t.dQ),qi:xi(t.qInv),alg:"RS256"}}function cV(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ts.default.pki.privateKeyToAsn1({n:gn(r.n),e:gn(r.e),d:gn(r.d),p:gn(r.p),q:gn(r.q),dP:gn(r.dp),dQ:gn(r.dq),qInv:gn(r.qi)});return G(Ts.default.asn1.toDer(e).getBytes(),"ascii")}function uV(r){let e=Ts.default.asn1.fromDer(U(r,"ascii")),t=Ts.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:xi(t.n),e:xi(t.e)}}function lV(r){if(r.n==null||r.e==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ts.default.pki.publicKeyToAsn1({n:gn(r.n),e:gn(r.e)});return G(Ts.default.asn1.toDer(e).getBytes(),"ascii")}async function Vx(r){let e=await qt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await $x(e);return{privateKey:t[0],publicKey:t[1]}}async function l4(r){let t=[await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await fV(r)],n=await $x({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function qx(r,e){let t=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function zx(r,e,t){let n=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function $x(r){if(r.privateKey==null||r.publicKey==null)throw new w("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([qt.get().subtle.exportKey("jwk",r.privateKey),qt.get().subtle.exportKey("jwk",r.publicKey)])}async function fV(r){return qt.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Hx(r,e,t,n){let i=e?Kx(r):Fx(r),s=U(Uint8Array.from(t),"ascii"),o=n(s,i);return G(o,"ascii")}function Gx(r,e){return Hx(r,!0,e,(t,n)=>n.encrypt(t))}function Wx(r,e){return Hx(r,!1,e,(t,n)=>n.decrypt(t))}function xd(r){if(r.kty!=="RSA")throw new w("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new w("invalid key modulus","ERR_INVALID_KEY_MODULUS");return G(r.n,"base64url").length*8}var rf=8192,tf=class{_key;constructor(e){this._key=e}async verify(e,t){return zx(this._key,t,e)}marshal(){return Ia.jwkToPkix(this._key)}get bytes(){return wi.encode({Type:yt.RSA,Data:this.marshal()}).subarray()}encrypt(e){return Gx(this._key,e)}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ke.digest(this.bytes);return e}},Uc=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return zn(16)}async sign(e){return qx(this._key,e)}get public(){if(this._publicKey==null)throw new w("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new tf(this._publicKey)}decrypt(e){return Wx(this._key,e)}marshal(){return Ia.jwkToPkcs1(this._key)}get bytes(){return Ei.encode({Type:yt.RSA,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ke.digest(this.bytes);return e}async id(){let e=await this.public.hash();return U(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new ef.default.util.ByteBuffer(this.marshal()),i=ef.default.asn1.fromDer(n),s=ef.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return ef.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(t==="libp2p-key")return Bc(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function dV(r){let e=Ia.pkcs1ToJwk(r);if(xd(e)>rf)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await l4(e);return new Uc(t.privateKey,t.publicKey)}function pV(r){let e=Ia.pkixToJwk(r);if(xd(e)>rf)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new tf(e)}async function mV(r){if(xd(r)>rf)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await l4(r);return new Uc(e.privateKey,e.publicKey)}async function gV(r){if(r>rf)throw new w("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Vx(r);return new Uc(e.privateKey,e.publicKey)}var g4={};be(g4,{Secp256k1PrivateKey:()=>sf,Secp256k1PublicKey:()=>nf,generateKeyPair:()=>PV,unmarshalSecp256k1PrivateKey:()=>DV,unmarshalSecp256k1PublicKey:()=>CV});var yV=(r,e,t)=>r&e^~r&t,bV=(r,e,t)=>r&e^r&t^e&t,wV=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]),mo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),go=new Uint32Array(64),vd=class extends Pc{constructor(){super(64,32,8,!1),this.A=mo[0]|0,this.B=mo[1]|0,this.C=mo[2]|0,this.D=mo[3]|0,this.E=mo[4]|0,this.F=mo[5]|0,this.G=mo[6]|0,this.H=mo[7]|0}get(){let{A:e,B:t,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,t,n,i,s,o,a,c]}set(e,t,n,i,s,o,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)go[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let h=go[f-15],d=go[f-2],p=mi(h,7)^mi(h,18)^h>>>3,m=mi(d,17)^mi(d,19)^d>>>10;go[f]=m+go[f-7]+p+go[f-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let h=mi(a,6)^mi(a,11)^mi(a,25),d=l+h+yV(a,c,u)+wV[f]+go[f]|0,m=(mi(n,2)^mi(n,13)^mi(n,22))+bV(n,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=n,n=d+m|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){go.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},h4=class extends vd{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}},Fc=lo(()=>new vd),vue=lo(()=>new h4);function EV(r){let e=Yl(r);pn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:i}=e;if(t){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:xV,hexToBytes:vV}=fd,Aa={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Aa;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:xV(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Aa,t=typeof r=="string"?vV(r):r;if(!(t instanceof Uint8Array))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:s}=Aa._parseInt(t.subarray(2)),{d:o,l:a}=Aa._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let l=u.toString(16);return l.length&1?`0${l}`:l},n=e(t(r.s)),i=e(t(r.r)),s=n.length/2,o=i.length/2,a=t(s),c=t(o);return`30${t(o+s+4)}02${c}${i}02${a}${n}`}},Ds=BigInt(0),$n=BigInt(1),Aue=BigInt(2),Yx=BigInt(3),Tue=BigInt(4);function _V(r){let e=EV(r),{Fp:t}=e,n=e.toBytes||((p,m,g)=>{let y=m.toAffine();return yi(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),i=e.fromBytes||(p=>{let m=p.subarray(1),g=t.fromBytes(m.subarray(0,t.BYTES)),y=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:g,y}});function s(p){let{a:m,b:g}=e,y=t.sqr(p),b=t.mul(y,p);return t.add(t.add(b,t.mul(p,m)),g)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function o(p){return typeof p=="bigint"&&Dst.eql(E,t.ZERO);return b(g)&&b(y)?f.ZERO:new f(g,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let g=t.invertBatch(m.map(y=>y.pz));return m.map((y,b)=>y.toAffine(g[b])).map(f.fromAffine)}static fromHex(m){let g=f.fromAffine(i(ot("pointHex",m)));return g.assertValidity(),g}static fromPrivateKey(m){return f.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint)return;throw new Error("bad point: ZERO")}let{x:m,y:g}=this.toAffine();if(!t.isValid(m)||!t.isValid(g))throw new Error("bad point: x or y not FE");let y=t.sqr(g),b=s(m);if(!t.eql(y,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){l(m);let{px:g,py:y,pz:b}=this,{px:E,py:_,pz:x}=m,v=t.eql(t.mul(g,x),t.mul(E,b)),R=t.eql(t.mul(y,x),t.mul(_,b));return v&&R}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:g}=e,y=t.mul(g,Yx),{px:b,py:E,pz:_}=this,x=t.ZERO,v=t.ZERO,R=t.ZERO,T=t.mul(b,b),P=t.mul(E,E),q=t.mul(_,_),$=t.mul(b,E);return $=t.add($,$),R=t.mul(b,_),R=t.add(R,R),x=t.mul(m,R),v=t.mul(y,q),v=t.add(x,v),x=t.sub(P,v),v=t.add(P,v),v=t.mul(x,v),x=t.mul($,x),R=t.mul(y,R),q=t.mul(m,q),$=t.sub(T,q),$=t.mul(m,$),$=t.add($,R),R=t.add(T,T),T=t.add(R,T),T=t.add(T,q),T=t.mul(T,$),v=t.add(v,T),q=t.mul(E,_),q=t.add(q,q),T=t.mul(q,$),x=t.sub(x,T),R=t.mul(q,P),R=t.add(R,R),R=t.add(R,R),new f(x,v,R)}add(m){l(m);let{px:g,py:y,pz:b}=this,{px:E,py:_,pz:x}=m,v=t.ZERO,R=t.ZERO,T=t.ZERO,P=e.a,q=t.mul(e.b,Yx),$=t.mul(g,E),Q=t.mul(y,_),te=t.mul(b,x),_e=t.add(g,y),k=t.add(E,_);_e=t.mul(_e,k),k=t.add($,Q),_e=t.sub(_e,k),k=t.add(g,b);let F=t.add(E,x);return k=t.mul(k,F),F=t.add($,te),k=t.sub(k,F),F=t.add(y,b),v=t.add(_,x),F=t.mul(F,v),v=t.add(Q,te),F=t.sub(F,v),T=t.mul(P,k),v=t.mul(q,te),T=t.add(v,T),v=t.sub(Q,T),T=t.add(Q,T),R=t.mul(v,T),Q=t.add($,$),Q=t.add(Q,$),te=t.mul(P,te),k=t.mul(q,k),Q=t.add(Q,te),te=t.sub($,te),te=t.mul(P,te),k=t.add(k,te),$=t.mul(Q,k),R=t.add(R,$),$=t.mul(F,k),v=t.mul(_e,v),v=t.sub(v,$),$=t.mul(_e,Q),T=t.mul(F,T),T=t.add(T,$),new f(v,R,T)}subtract(m){return this.add(m.negate())}is0(){return this.equals(f.ZERO)}wNAF(m){return d.wNAFCached(this,u,m,g=>{let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,E)=>b.toAffine(y[E])).map(f.fromAffine)})}multiplyUnsafe(m){let g=f.ZERO;if(m===Ds)return g;if(a(m),m===$n)return this;let{endo:y}=e;if(!y)return d.unsafeLadder(this,m);let{k1neg:b,k1:E,k2neg:_,k2:x}=y.splitScalar(m),v=g,R=g,T=this;for(;E>Ds||x>Ds;)E&$n&&(v=v.add(T)),x&$n&&(R=R.add(T)),T=T.double(),E>>=$n,x>>=$n;return b&&(v=v.negate()),_&&(R=R.negate()),R=new f(t.mul(R.px,y.beta),R.py,R.pz),v.add(R)}multiply(m){a(m);let g=m,y,b,{endo:E}=e;if(E){let{k1neg:_,k1:x,k2neg:v,k2:R}=E.splitScalar(g),{p:T,f:P}=this.wNAF(x),{p:q,f:$}=this.wNAF(R);T=d.constTimeNegate(_,T),q=d.constTimeNegate(v,q),q=new f(t.mul(q.px,E.beta),q.py,q.pz),y=T.add(q),b=P.add($)}else{let{p:_,f:x}=this.wNAF(g);y=_,b=x}return f.normalizeZ([y,b])[0]}multiplyAndAddUnsafe(m,g,y){let b=f.BASE,E=(x,v)=>v===Ds||v===$n||!x.equals(b)?x.multiplyUnsafe(v):x.multiply(v),_=E(this,g).add(E(m,y));return _.is0()?void 0:_}toAffine(m){let{px:g,py:y,pz:b}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(b));let _=t.mul(g,m),x=t.mul(y,m),v=t.mul(b,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:_,y:x}}isTorsionFree(){let{h:m,isTorsionFree:g}=e;if(m===$n)return!0;if(g)return g(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:g}=e;return m===$n?this:g?g(f,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(f,this,m)}toHex(m=!0){return Xi(this.toRawBytes(m))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,d=md(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:o}}function SV(r){let e=Yl(r);return pn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Qx(r){let e=SV(r),{Fp:t,n}=e,i=t.BYTES+1,s=2*t.BYTES+1;function o(k){return DsXi(Ss(k,e.nByteLength));function p(k){let F=n>>$n;return k>F}function m(k){return p(k)?a(-k):k}let g=(k,F,O)=>gi(k.slice(F,O));class y{constructor(F,O,M){this.r=F,this.s=O,this.recovery=M,this.assertValidity()}static fromCompact(F){let O=e.nByteLength;return F=ot("compactSignature",F,O*2),new y(g(F,0,O),g(F,O,2*O))}static fromDER(F){let{r:O,s:M}=Aa.toSig(ot("DER",F));return new y(O,M)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(F){return new y(this.r,this.s,F)}recoverPublicKey(F){let{r:O,s:M,recovery:A}=this,H=R(ot("msgHash",F));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let X=A===2||A===3?O+e.n:O;if(X>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let re=A&1?"03":"02",xe=u.fromHex(re+d(X)),Se=c(X),Be=a(-H*Se),Ae=a(M*Se),Ce=u.BASE.multiplyAndAddUnsafe(xe,Be,Ae);if(!Ce)throw new Error("point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return va(this.toDERHex())}toDERHex(){return Aa.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return va(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(k){try{return l(k),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let k=e.randomBytes(t.BYTES+8),F=cx(k,n);return Ss(F,e.nByteLength)},precompute(k=8,F=u.BASE){return F._setWindowSize(k),F.multiply(BigInt(3)),F}};function E(k,F=!0){return u.fromPrivateKey(k).toRawBytes(F)}function _(k){let F=k instanceof Uint8Array,O=typeof k=="string",M=(F||O)&&k.length;return F?M===i||M===s:O?M===2*i||M===2*s:k instanceof u}function x(k,F,O=!0){if(_(k))throw new Error("first arg must be private key");if(!_(F))throw new Error("second arg must be public key");return u.fromHex(F).multiply(l(k)).toRawBytes(O)}let v=e.bits2int||function(k){let F=gi(k),O=k.length*8-e.nBitLength;return O>0?F>>BigInt(O):F},R=e.bits2int_modN||function(k){return a(v(k))},T=Wl(e.nBitLength);function P(k){if(typeof k!="bigint")throw new Error("bigint expected");if(!(Ds<=k&&kit in O))throw new Error("sign() legacy options not supported");let{hash:M,randomBytes:A}=e,{lowS:H,prehash:X,extraEntropy:re}=O;H==null&&(H=!0),k=ot("msgHash",k),X&&(k=ot("prehashed msgHash",M(k)));let xe=R(k),Se=l(F),Be=[P(Se),P(xe)];if(re!=null){let it=re===!0?A(t.BYTES):re;Be.push(ot("extraEntropy",it,t.BYTES))}let Ae=yi(...Be),Ce=xe;function lt(it){let pr=v(it);if(!h(pr))return;let mr=c(pr),jt=u.BASE.multiply(pr).toAffine(),Tr=a(jt.x);if(Tr===Ds)return;let us=a(mr*a(Ce+Tr*Se));if(us===Ds)return;let Jo=(jt.x===Tr?0:2)|Number(jt.y&$n),ll=us;return H&&p(us)&&(ll=m(us),Jo^=1),new y(Tr,ll,Jo)}return{seed:Ae,k2sig:lt}}let $={lowS:e.lowS,prehash:!1},Q={lowS:e.lowS,prehash:!1};function te(k,F,O=$){let{seed:M,k2sig:A}=q(k,F,O),H=e;return W3(H.hash.outputLen,H.nByteLength,H.hmac)(M,A)}u.BASE._setWindowSize(8);function _e(k,F,O,M=Q){let A=k;if(F=ot("msgHash",F),O=ot("publicKey",O),"strict"in M)throw new Error("options.strict was renamed to lowS");let{lowS:H,prehash:X}=M,re,xe;try{if(typeof A=="string"||A instanceof Uint8Array)try{re=y.fromDER(A)}catch(jt){if(!(jt instanceof Aa.Err))throw jt;re=y.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:jt,s:Tr}=A;re=new y(jt,Tr)}else throw new Error("PARSE");xe=u.fromHex(O)}catch(jt){if(jt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(H&&re.hasHighS())return!1;X&&(F=e.hash(F));let{r:Se,s:Be}=re,Ae=R(F),Ce=c(Be),lt=a(Ae*Ce),it=a(Se*Ce),pr=u.BASE.multiplyAndAddUnsafe(xe,lt,it)?.toAffine();return pr?a(pr.x)===Se:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:x,sign:te,verify:_e,ProjectivePoint:u,Signature:y,utils:b}}var _d=class extends Cc{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,dn.hash(e);let n=uo(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;onew _d(r,e).update(t).digest();Kc.create=(r,e)=>new _d(r,e);function RV(r){return{hash:r,hmac:(e,...t)=>Kc(r,e,ad(...t)),randomBytes:fo}}function Xx(r,e){let t=n=>Qx({...r,...RV(n)});return Object.freeze({...t(e),create:t})}var Jx=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),jx=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),IV=BigInt(1),d4=BigInt(2),Zx=(r,e)=>(r+e/d4)/e;function AV(r){let e=Jx,t=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=gt(l,t,e)*l%e,h=gt(f,t,e)*l%e,d=gt(h,d4,e)*u%e,p=gt(d,i,e)*d%e,m=gt(p,s,e)*p%e,g=gt(m,a,e)*m%e,y=gt(g,c,e)*g%e,b=gt(y,a,e)*m%e,E=gt(b,t,e)*l%e,_=gt(E,o,e)*p%e,x=gt(_,n,e)*u%e,v=gt(x,d4,e);if(!p4.eql(p4.sqr(v),r))throw new Error("Cannot find square root");return v}var p4=pd(Jx,void 0,void 0,{sqrt:AV}),Cs=Xx({a:BigInt(0),b:BigInt(7),Fp:p4,n:jx,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=jx,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-IV*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=Zx(s*r,e),c=Zx(-n*r,e),u=je(r-a*t-c*i,e),l=je(-a*n-c*s,e),f=u>o,h=l>o;if(f&&(u=e-u),h&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:h,k2:l}}}},Fc),Gue=BigInt(0);var Wue=Cs.ProjectivePoint;function ev(){return Cs.utils.randomPrivateKey()}async function tv(r,e){let{digest:t}=await Ke.digest(e);try{return Cs.sign(t,r).toDERRawBytes()}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}async function rv(r,e,t){try{let{digest:n}=await Ke.digest(t);return Cs.verify(e,n,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}function nv(r){return Cs.ProjectivePoint.fromHex(r).toRawBytes(!0)}function iv(r){try{Cs.getPublicKey(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}function m4(r){try{Cs.ProjectivePoint.fromHex(r)}catch(e){throw new w(String(e),"ERR_INVALID_PUBLIC_KEY")}}function sv(r){try{return Cs.getPublicKey(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}var nf=class{_key;constructor(e){m4(e),this._key=e}async verify(e,t){return rv(this._key,t,e)}marshal(){return nv(this._key)}get bytes(){return wi.encode({Type:yt.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ke.digest(this.bytes);return e}},sf=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??sv(e),iv(this._key),m4(this._publicKey)}async sign(e){return tv(this._key,e)}get public(){return new nf(this._publicKey)}marshal(){return this._key}get bytes(){return Ei.encode({Type:yt.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ke.digest(this.bytes);return e}async id(){let e=await this.public.hash();return U(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Bc(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function DV(r){return new sf(r)}function CV(r){return new nf(r)}async function PV(){let r=ev();return new sf(r)}var ji={rsa:f4,ed25519:i4,secp256k1:g4};function y4(r){let e=Object.keys(ji).join(" / ");return new w(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function b4(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ji[r];throw y4(r)}async function of(r,e){return b4(r).generateKeyPair(e??2048)}async function kV(r,e,t){if(r.toLowerCase()!=="ed25519")throw new w("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return n4(e)}function vi(r){let e=wi.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case yt.RSA:return ji.rsa.unmarshalRsaPublicKey(t);case yt.Ed25519:return ji.ed25519.unmarshalEd25519PublicKey(t);case yt.Secp256k1:return ji.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw y4(e.Type??"RSA")}}function af(r,e){return e=(e??"rsa").toLowerCase(),b4(e),r.bytes}async function _i(r){let e=Ei.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case yt.RSA:return ji.rsa.unmarshalRsaPrivateKey(t);case yt.Ed25519:return ji.ed25519.unmarshalEd25519PrivateKey(t);case yt.Secp256k1:return ji.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw y4(e.Type??"RSA")}}function w4(r,e){return e=(e??"rsa").toLowerCase(),b4(e),r.bytes}async function Vc(r,e){try{let i=await Tx(r,e);return await _i(i)}catch{}let t=Sd.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new w("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Sd.default.asn1.toDer(Sd.default.pki.privateKeyToAsn1(t));return n=G(n.getBytes(),"ascii"),ji.rsa.unmarshalRsaPrivateKey(n)}var cf=Symbol.for("@libp2p/content-routing");var Ye=class extends EventTarget{#e=new Map;listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t){return this.dispatchEvent(new nt(e,t))}},E4=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},nt=globalThis.CustomEvent??E4;var Ta=Symbol.for("@libp2p/peer-discovery");var uf=Symbol.for("@libp2p/peer-routing");var gle=j(Q0(),1),NV=j(Ve(),1);var av=j(A3(),1),cv=j(Nt(),1),ov={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function lf(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(ov).join(" / ");throw new w(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=ov[i],o=(0,av.default)(r,e,t,n,s);return cv.default.encode64(o,null)}var x4=Symbol.for("@libp2p/peer-id");function Id(r){return r!=null&&!!r[x4]}var LV=Symbol.for("nodejs.util.inspect.custom"),uv=Object.values(Bn).map(r=>r.decoder).reduce((r,e)=>r.or(e),Bn.identity.decoder),lv=114,v4=36,_4=37,ff=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[x4]=!0;toString(){return this.string==null&&(this.string=Re.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Ne.createV1(lv,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return fe(this.multihash.bytes,e);if(typeof e=="string")return we(e).equals(this);if(e?.multihash?.bytes!=null)return fe(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[LV](){return`PeerId(${this.toString()})`}},Da=class extends ff{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ca=class extends ff{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Pa=class extends ff{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function fv(r){if(r.type==="RSA")return new Da(r);if(r.type==="Ed25519")return new Ca(r);if(r.type==="secp256k1")return new Pa(r);throw new w("Not a PeerId","ERR_INVALID_PARAMETERS")}function we(r,e){if(e=e??uv,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Ui(Re.decode(`z${r}`));return r.startsWith("12D")?new Ca({multihash:t}):r.startsWith("16U")?new Pa({multihash:t}):new Da({multihash:t})}return Ot(uv.decode(r))}function Ot(r){try{let e=Ui(r);if(e.code===Fi.code){if(e.digest.length===v4)return new Ca({multihash:e});if(e.digest.length===_4)return new Pa({multihash:e})}if(e.code===Ke.code)return new Da({multihash:e})}catch{return MV(Ne.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function MV(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==lv)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ke.code)return new Da({multihash:r.multihash});if(e.code===Fi.code){if(e.digest.length===v4)return new Ca({multihash:r.multihash});if(e.digest.length===_4)return new Pa({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Zr(r,e){return r.length===v4?new Ca({multihash:ii(Fi.code,r),privateKey:e}):r.length===_4?new Pa({multihash:ii(Fi.code,r),privateKey:e}):new Da({multihash:await Ke.digest(r),publicKey:r,privateKey:e})}var Ev=j(wv(),1),yo=Ev.default;var Cv=j(Dv(),1);var ze;(function(r){r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(ze||(ze={}));var Dd=C("libp2p:keychain"),rq="/pkcs8/",Pv="/info/",ka=new WeakMap,Na={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},R4={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function Ps(r){return r==null||typeof r!="string"?!1:r===(0,Cv.default)(r.trim())&&r.length>0}async function at(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function Zi(r){return new pt(rq+r)}function bo(r){return new pt(Pv+r)}var Oa=class{components;init;constructor(e,t){if(this.components=e,this.init=yo(R4,t),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLengthi.id===e);if(n==null)throw new w(`Key with id '${e}' does not exist.`,ze.ERR_KEY_NOT_FOUND);return n}catch(t){throw await at(),t}}async findKeyByName(e){if(!Ps(e))throw await at(),new w(`Invalid key name '${e}'`,ze.ERR_INVALID_KEY_NAME);let t=bo(e);try{let n=await this.components.datastore.get(t);return JSON.parse(U(n))}catch(n){throw await at(),Dd.error(n),new w(`Key '${e}' does not exist.`,ze.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!Ps(e)||e==="self")throw await at(),new w(`Invalid key name '${e}'`,ze.ERR_INVALID_KEY_NAME);let t=Zi(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(bo(e)),await i.commit(),n}async renameKey(e,t){if(!Ps(e)||e==="self")throw await at(),new w(`Invalid old key name '${e}'`,ze.ERR_OLD_KEY_NAME_INVALID);if(!Ps(t)||t==="self")throw await at(),new w(`Invalid new key name '${t}'`,ze.ERR_NEW_KEY_NAME_INVALID);let n=Zi(e),i=Zi(t),s=bo(e),o=bo(t);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${t}' already exists`,ze.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(s),l=JSON.parse(U(u));l.name=t;let f=this.components.datastore.batch();return f.put(i,c),f.put(o,G(JSON.stringify(l))),f.delete(n),f.delete(s),await f.commit(),l}catch(c){throw await at(),c}}async exportKey(e,t){if(!Ps(e))throw await at(),new w(`Invalid key name '${e}'`,ze.ERR_INVALID_KEY_NAME);if(t==null)throw await at(),new w("Password is required",ze.ERR_PASSWORD_REQUIRED);let n=Zi(e);try{let i=await this.components.datastore.get(n),s=U(i),o=ka.get(this);if(o==null)throw new w("dek missing",ze.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Vc(s,a)).export(t)}catch(i){throw await at(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await Vc(n,t);return Zr(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!Ps(e)||e==="self")throw await at(),new w(`Invalid key name '${e}'`,ze.ERR_INVALID_KEY_NAME);if(t==null)throw await at(),new w("PEM encoded key is required",ze.ERR_PEM_REQUIRED);let i=Zi(e);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${e}' already exists`,ze.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Vc(t,n)}catch{throw await at(),new w("Cannot read the key, most likely the password is wrong",ze.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let l=ka.get(this);if(l==null)throw new w("dek missing",ze.ERR_INVALID_PARAMETERS);let f=l.dek;t=await o.export(f)}catch(l){throw await at(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,G(t)),u.put(bo(e),G(JSON.stringify(c))),await u.commit(),c}async importPeer(e,t){try{if(!Ps(e))throw new w(`Invalid key name '${e}'`,ze.ERR_INVALID_KEY_NAME);if(t==null)throw new w("PeerId is required",ze.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw new w("PeerId.privKey is required",ze.ERR_MISSING_PRIVATE_KEY);let n=await _i(t.privateKey),i=Zi(e);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${e}' already exists`,ze.ERR_KEY_ALREADY_EXISTS);let o=ka.get(this);if(o==null)throw new w("dek missing",ze.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),u={name:e,id:t.toString()},l=this.components.datastore.batch();return l.put(i,G(c)),l.put(bo(e),G(JSON.stringify(u))),await l.commit(),u}catch(n){throw await at(),n}}async getPrivateKey(e){if(!Ps(e))throw await at(),new w(`Invalid key name '${e}'`,ze.ERR_INVALID_KEY_NAME);try{let t=Zi(e),n=await this.components.datastore.get(t);return U(n)}catch(t){throw await at(),Dd.error(t),new w(`Key '${e}' does not exist.`,ze.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await at(),new w(`Invalid old pass type '${typeof e}'`,ze.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await at(),new w(`Invalid new pass type '${typeof t}'`,ze.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await at(),new w(`Invalid pass length ${t.length}`,ze.ERR_INVALID_PASS_LENGTH);Dd("recreating keychain");let n=ka.get(this);if(n==null)throw new w("dek missing",ze.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?lf(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";ka.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Zi(a.name)),u=U(c),l=await Vc(u,i),f=s.toString(),h=await l.export(f),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Zi(a.name),G(h)),d.put(bo(a.name),G(JSON.stringify(p))),await d.commit()}Dd("keychain reconstructed")}};function ks(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var kr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return ks(this.map.entries(),e=>[we(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,we(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return ks(this.map.keys(),e=>we(e))}values(){return this.map.values()}get size(){return this.map.size}};var Hn=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return ks(this.set.entries(),e=>{let t=we(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=we(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ks(this.set.values(),e=>we(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var I4=class r{list;constructor(e){if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return ks(this.list.entries(),e=>we(e[1]))}concat(e){let t=new r(this);for(let n of e)t.push(n);return t}entries(){return ks(this.list.entries(),e=>[e[0],we(e[1])])}every(e){return this.list.every((t,n)=>e(we(t),n,this))}filter(e){let t=new r;return this.list.forEach((n,i)=>{let s=we(n);e(s,i,this)&&t.push(s)}),t}find(e){let t=this.list.find((n,i)=>e(we(n),i,this));if(t!=null)return we(t)}findIndex(e){return this.list.findIndex((t,n)=>e(we(t),n,this))}forEach(e){this.list.forEach((t,n)=>{e(we(t),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return we(e)}push(...e){for(let t of e)this.list.push(t.toString())}shift(){let e=this.list.shift();if(e!=null)return we(e)}unshift(...e){let t=this.list.length;for(let n=e.length-1;n>-1;n--)t=this.list.unshift(e[n].toString());return t}get length(){return this.list.length}};var A4;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(A4||(A4={}));var Cd=async()=>{let r=await of("Ed25519"),e=await nq(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function nq(r){return Zr(af(r.public),w4(r))}function Pd(r){return r instanceof Uint8Array?{get(e){return r[e]},set(e,t){r[e]=t}}:{get(e){return r.get(e)},set(e,t){r.set(e,t)}}}var kv=4294967296,hf=class r{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),t=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new r(n,t)}zzEncode(){let e=this.hi>>31,t=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new r(t,n)}toBytes(e,t=0){let n=Pd(e);for(;this.hi>0;)n.set(t++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(t++,this.lo&127|128),this.lo=this.lo>>>7;n.set(t++,this.lo)}static fromBigInt(e){if(e===0n)return new r;let t=e<0;t&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return t&&(n=~n>>>0,i=~i>>>0,++i>kv&&(i=0,++n>kv&&(n=0))),new r(n,i)}static fromNumber(e){if(e===0)return new r;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(i,n)}static fromBytes(e,t=0){let n=Pd(e),i=new r,s=0;if(e.length-t>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(t)&127)<>>0,n.get(t++)<128)return i;if(i.lo=(i.lo|(n.get(t)&127)<<28)>>>0,i.hi=(i.hi|(n.get(t)&127)>>4)>>>0,n.get(t++)<128)return i;s=0}else for(;s<4;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(t)&127)<>>0,n.get(t++)<128)return i}else if(t=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var iq=Math.pow(2,7),sq=Math.pow(2,14),oq=Math.pow(2,21),aq=Math.pow(2,28),cq=Math.pow(2,35),uq=Math.pow(2,42),lq=Math.pow(2,49),fq=Math.pow(2,56),hq=Math.pow(2,63),df={encodingLength(r){return rNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Mr(df.encodingLength(r))),hf.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return hf.fromBytes(r,e).toNumber(!0)}};var Nv={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var pf;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(pf||(pf={}));var Gn=class r{static createFromProtobuf=async e=>{let t=pf.decode(e),n=await Zr(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,i=e.codec,s=e.marshal(),o=Ov(n,i,s),c=await(await _i(t.privateKey)).sign(o.subarray());return new r({peerId:t,payloadType:i,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new w("envelope signature is not valid for the given domain",Nv.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:i,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=pf.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return fe(this.marshal(),e.marshal())}async validate(e){let t=Ov(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return vi(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Ov=(r,e,t)=>{let n=G(r),i=df.encode(n.byteLength),s=df.encode(e.length),o=df.encode(t.length);return new Te(i,n,s,e,o,t)};function Bv(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var kd=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let s=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(s*=e,s+=l,s>u||(o+=1,t!==void 0&&o>t))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;nthis.readIPv4Addr());if(o!==void 0)return t[i]=o[0],t[i+1]=o[1],t[i+2]=o[2],t[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];t[i]=s>>8,t[i+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Lv=45,dq=15,$c=new kd;function T4(r){if(!(r.length>dq))return $c.new(r).parseWith(()=>$c.readIPv4Addr())}function D4(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Lv))return $c.new(r).parseWith(()=>$c.readIPv6Addr())}function Nd(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Lv))return $c.new(r).parseWith(()=>$c.readIPAddr())}var jfe=parseInt("0xFFFF",16),Zfe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Od(r){return!!T4(r)}function Bd(r){return!!D4(r)}function Hc(r){return!!Nd(r)}var Fv=Od,bq=Bd,C4=function(r){let e=0;if(r=r.toString().trim(),Fv(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(bq(r)){let t=r.split(":",8),n;for(n=0;n0;n--)s.push("0");t.splice.apply(t,s)}let i=new Uint8Array(e+16);for(n=0;n>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},Kv=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let i=[];for(let s=0;s{let e=xq(...r);P4[e.code]=e,Gc[e.name]=e});function xq(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function le(r){if(typeof r=="number"){if(P4[r]!=null)return P4[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Gc[r]!=null)return Gc[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Bhe=le("ip4"),Lhe=le("ip6"),Mhe=le("ipcidr");function mf(r,e){switch(le(r).code){case 4:case 41:return _q(e);case 42:return zv(e);case 6:case 273:case 33:case 132:return Hv(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return zv(e);case 421:return Aq(e);case 444:return $v(e);case 445:return $v(e);case 466:return Iq(e);default:return U(e,"base16")}}function N4(r,e){switch(le(r).code){case 4:return Vv(e);case 41:return Vv(e);case 42:return qv(e);case 6:case 273:case 33:case 132:return O4(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qv(e);case 421:return Sq(e);case 444:return Tq(e);case 445:return Dq(e);case 466:return Rq(e);default:return G(e,"base16")}}var k4=Object.values(Bn).map(r=>r.decoder),vq=function(){let r=k4[0].or(k4[1]);return k4.slice(2).forEach(e=>r=r.or(e)),r}();function Vv(r){if(!Hc(r))throw new Error("invalid ip address");return C4(r)}function _q(r){let e=Kv(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Hc(e))throw new Error("invalid ip address");return e}function O4(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Hv(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function qv(r){let e=G(r),t=Uint8Array.from(Qr(e.length));return ve([t,e],t.length+e.length)}function zv(r){let e=on(r);if(r=r.slice(sr(e)),r.length!==e)throw new Error("inconsistent lengths");return U(r)}function Sq(r){let e;r[0]==="Q"||r[0]==="1"?e=Ui(Re.decode(`z${r}`)).bytes:e=Ne.parse(r).multihash.bytes;let t=Uint8Array.from(Qr(e.length));return ve([t,e],t.length+e.length)}function Rq(r){let e=vq.decode(r),t=Uint8Array.from(Qr(e.length));return ve([t,e],t.length+e.length)}function Iq(r){let e=on(r),t=r.slice(sr(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+U(t,"base64url")}function Aq(r){let e=on(r),t=r.slice(sr(e));if(t.length!==e)throw new Error("inconsistent lengths");return U(t,"base58btc")}function Tq(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Zt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=O4(n);return ve([t,i],t.length+i.length)}function Dq(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Zt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=O4(n);return ve([t,i],t.length+i.length)}function $v(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=U(e,"base32"),i=Hv(t);return`${n}:${i}`}function Gv(r){r=B4(r);let e=[],t=[],n=null,i=r.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s=i.length)throw Yv("invalid address: "+r);if(a.path===!0){n=B4(i.slice(s).join("/")),e.push([a.code,N4(a.code,n)]),t.push([a.code,n]);break}let c=N4(a.code,i[s]);e.push([a.code,c]),t.push([a.code,mf(a.code,c)])}return{string:Wv(t),bytes:M4(e),tuples:e,stringTuples:t,path:n}}function L4(r){let e=[],t=[],n=null,i=0;for(;ir.length)throw Yv("Invalid address Uint8Array: "+U(r,"base16"));e.push([s,u]);let l=mf(s,u);if(t.push([s,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:Wv(t),tuples:e,stringTuples:t,path:n}}function Wv(r){let e=[];return r.map(t=>{let n=le(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),B4(e.join("/"))}function M4(r){return ve(r.map(e=>{let t=le(e[0]),n=Uint8Array.from(Qr(t.code));return e.length>1&&e[1]!=null&&(n=ve([n,e[1]])),n}))}function Cq(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=on(e instanceof Uint8Array?e:Uint8Array.from(e));return t+sr(t)}}function B4(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Yv(r){return new Error("Error parsing address: "+r)}var Pq=Symbol.for("nodejs.util.inspect.custom"),kq=[le("dns").code,le("dns4").code,le("dns6").code,le("dnsaddr").code],F4=new Map,Qv=Symbol.for("@multiformats/js-multiaddr/multiaddr");function Ba(r){return!!r?.[Qv]}var U4=class r{bytes;#e;#t;#r;#n;[Qv]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=L4(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Gv(e)}else if(Ba(e))t=L4(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,i,s="",o=le("tcp"),a=le("udp"),c=le("ip4"),u=le("ip6"),l=le("dns6"),f=le("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(s=`%${p??""}`),kq.includes(d)&&(t=o.name,i=443,n=`${p??""}${s}`,e=d===l.code?6:4),(d===o.code||d===a.code)&&(t=le(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=le(d).name,n=`${p??""}${s}`,e=d===u.code?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}protos(){return this.#t.map(([e])=>Object.assign({},le(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>le(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,i))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(M4(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,i])=>{n===Gc.p2p.code&&e.push([n,i]),n===Gc["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?U(Re.decode(`z${n}`),"base58btc"):U(Ne.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return fe(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=F4.get(t.name);if(n==null)throw new w(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new r(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Pq](){return`Multiaddr(${this.#e})`}};function ge(r){return new U4(r)}var Xv="libp2p-peer-record",jv=Uint8Array.from([3,1]);var gf;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=me((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>pe(s,n.codec()),n.decode=s=>de(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=me((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>pe(n,r.codec()),r.decode=n=>de(n,r.codec())})(gf||(gf={}));var yn=class r{static createFromProtobuf=e=>{let t=gf.decode(e),n=Ot(t.peerId),i=(t.addresses??[]).map(o=>ge(o.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:i,seqNumber:s})};static DOMAIN=Xv;static CODEC=jv;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=gf.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Bv(this.multiaddrs,e.multiaddrs))}};var yr={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Wc;(function(r){let e;(function(i){let s;i.codec=()=>(s==null&&(s=me((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>pe(o,i.codec()),i.decode=o=>de(o,i.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let s;i.codec=()=>(s==null&&(s=me((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),Md.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},u=a==null?o.len:o.pos+a;for(;o.pos>>3){case 1:c.key=o.string();break;case 2:c.value=Md.codec().decode(o,o.uint32());break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>pe(o,i.codec()),i.decode=o=>de(o,i.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),Ld.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.addresses.push(Ld.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(Wc||(Wc={}));var Ld;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(Ld||(Ld={}));var Md;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.value=t.uint32();break;case 2:i.expiry=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(Md||(Md={}));function Yc(r,e){let t=Wc.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=fv({...r,publicKey:r.publicKey}));let n=new Map,i=BigInt(Date.now());for(let[s,o]of t.tags.entries())o.expiry!=null&&o.expiry({multiaddr:ge(s),isCertified:o??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var K4="/peers/";function Qc(r){if(!Id(r)||r.type==null)throw new w("Invalid PeerId",yr.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new pt(`${K4}${e}`)}async function Zv(r,e,t){let n=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=ge(i.multiaddr)),!Ba(i.multiaddr))throw new w("Multiaddr was invalid",yr.ERR_INVALID_PARAMETERS);if(!await e(r,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function Fd(r,e,t,n){if(e==null)throw new w("Invalid PeerData",yr.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!fe(e.publicKey,r.publicKey))throw new w("publicKey bytes do not match peer id publicKey bytes",yr.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!r.equals(i.id))throw new w("peer id did not match existing peer id",yr.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ud(f,{validate:Jv})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ud(f,{validate:e_,map:t_})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,d]of f)d==null?a.delete(h):a.set(h,d);a=Ud([...a.entries()],{validate:Jv})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[d,p]of f)p==null?h.delete(d):h.set(d,p);c=Ud([...h.entries()],{validate:e_,map:t_})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await Zv(r,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Ud(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([s],[o])=>s.localeCompare(o)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function Jv(r,e){if(typeof r!="string")throw new w("Metadata key must be a string",yr.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new w("Metadata value must be a Uint8Array",yr.ERR_INVALID_PARAMETERS)}function e_(r,e){if(typeof r!="string")throw new w("Tag name must be a string",yr.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new w("Tag value must be an integer",yr.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new w("Tag value must be between 0-100",yr.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new w("Tag ttl must be an integer",yr.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new w("Tag ttl must be between greater than 0",yr.ERR_INVALID_PARAMETERS)}}function t_(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Kd(r,e,t){let n=r.toString().split("/")[2],i=Zt.decode(n),s=Ot(i),o=t.get(s);if(o!=null)return o;let a=Yc(s,e);return t.set(s,a),a}function Nq(r,e){return r==null?{}:{prefix:K4,filters:(r.filters??[]).map(t=>({key:n,value:i})=>t(Kd(n,i,e))),orders:(r.orders??[]).map(t=>(n,i)=>t(Kd(n.key,n.value,e),Kd(i.key,i.value,e)))}}var Vd=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Kl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Qc(e))}async delete(e){if(this.peerId.equals(e))throw new w("Cannot delete self peer",yr.ERR_INVALID_PARAMETERS);await this.datastore.delete(Qc(e))}async load(e){let t=await this.datastore.get(Qc(e));return Yc(e,t)}async save(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await Fd(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await Fd(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await Fd(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(e){let t=new kr;for await(let{key:n,value:i}of this.datastore.query(Nq(e??{},t))){let s=Kd(n,i,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Qc(e)),n=Yc(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,i){let s=Wc.encode(t);return n!=null&&fe(s,n)?{peer:Yc(e,s),previous:i,updated:!1}:(await this.datastore.put(Qc(e),s),{peer:Yc(e,s),previous:i,updated:!0})}};var dt=C("libp2p:peer-store"),qd=class{store;events;peerId;constructor(e,t={}){this.events=e.events,this.peerId=e.peerId,this.store=new Vd(e,t)}async forEach(e,t){dt.trace("forEach await read lock");let n=await this.store.lock.readLock();dt.trace("forEach got read lock");try{for await(let i of this.store.all(t))e(i)}finally{dt.trace("forEach release read lock"),n()}}async all(e){dt.trace("all await read lock");let t=await this.store.lock.readLock();dt.trace("all got read lock");try{return await bl(this.store.all(e))}finally{dt.trace("all release read lock"),t()}}async delete(e){dt.trace("delete await write lock");let t=await this.store.lock.writeLock();dt.trace("delete got write lock");try{await this.store.delete(e)}finally{dt.trace("delete release write lock"),t()}}async has(e){dt.trace("has await read lock");let t=await this.store.lock.readLock();dt.trace("has got read lock");try{return await this.store.has(e)}finally{dt.trace("has release read lock"),t()}}async get(e){dt.trace("get await read lock");let t=await this.store.lock.readLock();dt.trace("get got read lock");try{return await this.store.load(e)}finally{dt.trace("get release read lock"),t()}}async save(e,t){dt.trace("save await write lock");let n=await this.store.lock.writeLock();dt.trace("save got write lock");try{let i=await this.store.save(e,t);return this.#e(e,i),i.peer}finally{dt.trace("save release write lock"),n()}}async patch(e,t){dt.trace("patch await write lock");let n=await this.store.lock.writeLock();dt.trace("patch got write lock");try{let i=await this.store.patch(e,t);return this.#e(e,i),i.peer}finally{dt.trace("patch release write lock"),n()}}async merge(e,t){dt.trace("merge await write lock");let n=await this.store.lock.writeLock();dt.trace("merge got write lock");try{let i=await this.store.merge(e,t);return this.#e(e,i),i.peer}finally{dt.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Gn.openAndCertify(e,yn.DOMAIN);if(t?.equals(n.peerId)===!1)return dt("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let i=yn.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await Gn.createFromProtobuf(s.peerRecordEnvelope),a=yn.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return dt("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function r_(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Oq=C("libp2p:address-manager"),Bq=r=>r;function V4(r,e){let t=r.getPeerId();return t!=null&&we(t).equals(e)&&(r=r.decapsulate(ge(`/p2p/${e.toString()}`))),r}var zd=class{components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Bq,this._updatePeerStoreAddresses=r_(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>ge(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{Oq.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>ge(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>ge(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>ge(e))}addObservedAddr(e){e=V4(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=V4(e,this.components.peerId);let t=e.toString(),i=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=V4(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>ge(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function n_(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var q4=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>n_(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Lq=["metrics","connectionProtector"],Mq=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function i_(r={}){let e=new q4(r);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!Mq.includes(i)){let o=e.components[i];if(o==null&&!Lq.includes(i))throw new w(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}var f_=j(s_(),1);var o_="[a-fA-F\\d:]",wo=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${o_})|(?<=${o_})(?=\\s|$))`:"",Si="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Qt="[a-fA-F\\d]{1,4}",$d=` (?: (?:${Qt}:){7}(?:${Qt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 (?:${Qt}:){6}(?:${Si}|:${Qt}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 (?:${Qt}:){5}(?::${Si}|(?::${Qt}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4 (?:${Qt}:){4}(?:(?::${Qt}){0,1}:${Si}|(?::${Qt}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4 (?:${Qt}:){3}(?:(?::${Qt}){0,2}:${Si}|(?::${Qt}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4 (?:${Qt}:){2}(?:(?::${Qt}){0,3}:${Si}|(?::${Qt}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4 (?:${Qt}:){1}(?:(?::${Qt}){0,4}:${Si}|(?::${Qt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 (?::(?:(?::${Qt}){0,5}:${Si}|(?::${Qt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Uq=new RegExp(`(?:^${Si}$)|(?:^${$d}$)`),Fq=new RegExp(`^${Si}$`),Kq=new RegExp(`^${$d}$`),z4=r=>r&&r.exact?Uq:new RegExp(`(?:${wo(r)}${Si}${wo(r)})|(?:${wo(r)}${$d}${wo(r)})`,"g");z4.v4=r=>r&&r.exact?Fq:new RegExp(`${wo(r)}${Si}${wo(r)}`,"g");z4.v6=r=>r&&r.exact?Kq:new RegExp(`${wo(r)}${$d}${wo(r)}`,"g");var a_=z4;var h_=j(u_(),1),{isValid:Vq,parse:qq}=h_.default,zq=["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"],$q=zq.map(r=>new f_.Netmask(r));function Hq(r){for(let e of $q)if(e.contains(r))return!0;return!1}function l_(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}var d_=r=>{if(Vq(r)){let e=qq(r);if(e.kind()==="ipv4")return Hq(e.toNormalizedString());if(e.kind()==="ipv6")return l_(r)}else if(Hc(r)&&a_.v6().test(r))return l_(r)};var Jr=d_;function p_(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Jr(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var Ji=Symbol.for("@libp2p/transport");var Eo;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Eo||(Eo={}));function $4(r){try{let{address:e}=r.nodeAddress();return!!Jr(e)}catch{return!0}}function Xc(r,e){let t=$4(r.multiaddr),n=$4(e.multiaddr);return t&&!n?1:!t&&n||r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}var G4=j(Uh(),1),W4=j(y_(),1);var b_=globalThis.fetch,w_=globalThis.Headers,Rde=globalThis.Request,Ide=globalThis.Response;function Gd(r,e,t){return`${r}?name=${e}&type=${t}`}async function E_(r,e){return await(await b_(r,{headers:new w_({accept:"application/dns-json"}),signal:e})).json()}function La(r,e){return`${e}_${r}`}var H4=Object.assign((0,G4.default)("dns-over-http-resolver"),{error:(0,G4.default)("dns-over-http-resolver:error")}),Y4=class{constructor(e={}){this._cache=new W4.default({max:e?.maxCache??100}),this._TXTcache=new W4.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??E_,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*t),i=e[t];e[t]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(La(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(Gd(s,e,t),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(La(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),H4.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){let t="AAAA",n=this._cache.get(La(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(Gd(s,e,t),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(La(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),H4.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){let t="TXT",n=this._TXTcache.get(La(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(Gd(s,e,t),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(La(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),H4.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},x_=Y4;var v_=x_;var{code:Xq}=le("dnsaddr");async function jc(r,e={}){let t=new v_;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,i]=r.stringTuples().find(([a])=>a===Xq)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await t.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var es;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.DHT_DISABLED="DHT is not available",r.PUBSUB_DISABLED="PubSub is not available",r.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",r.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(es||(es={}));var Y;(function(r){r.DHT_DISABLED="ERR_DHT_DISABLED",r.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",r.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",r.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",r.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",r.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TIMEOUT="ERR_TIMEOUT",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(Y||(Y={}));var jq={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:jc},addressSorter:Xc},transportManager:{faultTolerance:Eo.FATAL_ALL}};function __(r){let e=yo(jq,r);if(e.transports==null||e.transports.length<1)throw new w(es.ERR_TRANSPORTS_REQUIRED,Y.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new w(es.ERR_PROTECTOR_REQUIRED,Y.ERR_PROTECTOR_REQUIRED);return e}var S_="keep-alive";var vS=j(ug(),1);var Nz=C("libp2p:get-peer");function Yd(r){if(Id(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:we(t),r.forEach(n=>{if(!Ba(n))throw Nz.error("multiaddr %s was invalid",n),new w("Invalid Multiaddr",Y.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new w("Multiaddrs must all have the same peer id or have no peer id",Y.ERR_INVALID_PARAMETERS)}else{let s=we(i);if(e==null||!e.equals(s))throw new w("Multiaddrs must all have the same peer id or have no peer id",Y.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function Oz(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var lg=class{#e=[];enqueue(e,t){let n=t?.peerId,i=t?.priority??0;if(n==null)throw new w("missing peer id",Y.ERR_INVALID_PARAMETERS);let s={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(s);return}let o=Oz(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(o,0,s)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let t=e.peerId;return this.#e.filter(n=>t.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}},ru=class extends kt{constructor(e={}){super({...e,queueClass:lg})}hasJob(e){return this.sizeBy({peerId:e})>0}};var Qd="last-dial-failure";var Xd=10,jd=5,vo=100,Zd=10;var br=C("libp2p:connection-manager:auto-dial"),nu={minConnections:jd,maxQueueLength:100,autoDialConcurrency:Zd,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:6e4},Jd=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialInterval;started;running;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??nu.minConnections,this.autoDialPriority=t.autoDialPriority??nu.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??nu.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??nu.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??nu.autoDialPeerRetryThreshold,this.started=!1,this.running=!1,this.queue=new ru({concurrency:t.autoDialConcurrency??nu.autoDialConcurrency}),this.queue.addListener("error",n=>{br.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{br.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{br.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{br.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&br.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){br("not enough connections %d/%d but auto dial queue is full",t,this.minConnections);return}if(this.running){br("not enough connections %d/%d - but skipping autodial as it is already running",t,this.minConnections);return}this.running=!0,br("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Hn(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(br.trace("not autodialing %p because they have no addresses"),!1):e.has(u.id)?(br.trace("not autodialing %p because they are already connected"),!1):n.has(u.id)?(br.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(u.id)?(br.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),s=i.sort(()=>Math.random()>.5?1:-1),o=new kr;for(let u of s)o.has(u.id)||o.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=s.sort((u,l)=>{let f=o.get(u.id)??0,h=o.get(l.id)??0;return f>h?-1:f{let l=u.metadata.get(Qd);if(l==null)return!0;let f=parseInt(U(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});br("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){br("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}br("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{br.error("could not connect to peerStore stored peer",l)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(u=>{br.error("error while autodialing",u)})},this.autoDialIntervalMs))}};var iu=C("libp2p:connection-manager:connection-pruner"),wS={maxConnections:vo,allow:[]},e1=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,t={}){this.maxConnections=t.maxConnections??wS.maxConnections,this.allow=t.allow??wS.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{iu.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=Math.max(t-this.maxConnections,0);if(iu("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;iu("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let i=new kr;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&iu.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(uh?-1:0}),o=[];for(let a of s)if(iu("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){iu.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var mg=j(Xr(),1);var dg=j(Xr(),1);var ES=C("libp2p:connection-manager:utils");async function pg(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await Mz(r,e),o=(await Promise.all(n.map(async a=>pg(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return ES("resolved %s to",r,o.map(a=>a.toString())),o}async function Mz(r,e){try{return r=ge(r.toString()),await r.resolve(e)}catch(t){return ES.error(`multiaddr ${r.toString()} could not be resolved`,t),[]}}function xS(...r){let e=[];for(let n of r)if(n!=null){try{(0,dg.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let t=er(e);try{(0,dg.setMaxListeners)?.(1/0,t)}catch{}return t}var wr=C("libp2p:connection-manager:dial-queue"),wf={addressSorter:Xc,maxParallelDials:Xd,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:jc}},t1=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,t={}){this.addressSorter=t.addressSorter??wf.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??wf.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=t.maxParallelDialsPerPeer??wf.maxParallelDialsPerPeer,this.dialTimeout=t.dialTimeout??wf.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,mg.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(t.resolvers??{}))F4.set(n,i);this.queue=new kt({concurrency:t.maxParallelDials??wf.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{wr.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:i}=Yd(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(t.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...t,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return wr("joining existing dial target for %p",n),o.clear(),c.promise;wr("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:Fz(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...t,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(async l=>{if(wr.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),n!=null)try{await this.peerStore.patch(n,{metadata:{[Qd]:G(Date.now().toString())}})}catch(f){wr.error("could not update last dial failure key for %p",n,f)}throw o.aborted?new w(l.message,Y.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let t=er([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,mg.setMaxListeners)?.(1/0,t)}catch{}return t}async calculateMultiaddrs(e,t=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new w("Tried to dial self",Y.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new w("The dial request is blocked by gater.allowDialPeer",Y.ERR_PEER_DIAL_INTERCEPTED);if(t.length===0){wr("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);t.push(...l.addresses),wr("loaded multiaddrs for %p",e,t.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==Y.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(t.map(async l=>{let f=await pg(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),s=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),o=new Map;for(let l of s){let f=l.multiaddr.toString(),h=o.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(wr("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),wr("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new w("The dial request has no valid addresses",Y.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new w("dial with more addresses than allowed",Y.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new w("The connection gater denied all addresses in the dial request",Y.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,t={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new kt({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{wr.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new w("dialAction did not come with an AbortController",Y.ERR_INVALID_PARAMETERS);let u=xS(c.signal,t.signal);u.addEventListener("abort",()=>{wr("dial to %a aborted",o)});let l=Le();return await i.add(async()=>{if(u.aborted){wr("dial to %a was aborted before reaching the head of the peer dial queue",o),l.reject(new ai);return}await this.queue.add(async()=>{try{if(u.aborted){wr("dial to %a was aborted before reaching the head of the dial queue",o),l.reject(new ai);return}e.status="active";let f=await this.transportManager.dial(o,{...t,signal:u});if(c.signal.aborted){wr("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{wr.error("error closing superfluous connection",h)}),l.reject(new ai);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),wr("dial to %a succeeded",o),l.resolve(f)}catch(f){wr.error("error during dial of %a",o,f),l.reject(f)}},{...t,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new w("successful dial led to empty object returned from peer dial queue",Y.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function Fz(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var wn=C("libp2p:connection-manager"),qz=50,Ma={minConnections:jd,maxConnections:vo,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:Zd,autoDialPriority:0,autoDialMaxQueueLength:100},r1=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,t={}){this.maxConnections=t.maxConnections??Ma.maxConnections;let n=t.minConnections??Ma.minConnections;if(this.maxConnectionsge(i)),this.deny=(t.deny??[]).map(i=>ge(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Ma.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new vS.RateLimiterMemory({points:t.inboundConnectionThreshold??Ma.inboundConnectionThreshold,duration:1}),this.autoDial=new Jd({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Ma.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Ma.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??Ma.autoDialMaxQueueLength}),this.connectionPruner=new e1({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new t1({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:t.addressSorter??Xc,maxParallelDials:t.maxParallelDials??Xd,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:jc}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let i of n.streams){let s=`${i.direction} ${i.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.direction} ${o.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let t={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);t[n]=i[s]}return t}}),this.autoDial.start(),this.started=!0,wn("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(S_)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{wn.error(n)})}))}).catch(e=>{wn.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){wn.error(i)}})());wn("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),wn("stopped")}onConnect(e){this._onConnect(e).catch(t=>{wn.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==t.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new w("Not started",Y.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=Yd(e);if(n!=null&&t.force!==!0){wn("dial %p",n);let a=this.getConnections(n);if(a.length>0)return wn("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??qz}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(t)}catch(s){i.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return wn("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return wn("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return wn("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length(await e.merge(t.id,{multiaddrs:t.multiaddrs}),t))}function n1(r){let e=new Set;return Lr(r,t=>e.has(t.id.toString())?!1:(e.add(t.id.toString()),!0))}async function*i1(r,e=1){let t=0;for await(let n of r)t++,yield n;if(tn.findProviders(e,t))),n=>Ef(n,this.components.peerStore),n=>n1(n),n=>i1(n))}async provide(e,t={}){if(this.routers.length===0)throw new w("No content routers available",Y.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new w(es.NOT_STARTED_YET,Y.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new w(es.NOT_STARTED_YET,Y.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};function zz(r){return r[Symbol.asyncIterator]!=null}function $z(r){if(zz(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Ns=$z;var Hz=C("libp2p:peer-routing"),o1=class{components;routers;constructor(e,t){this.components=e,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new w("No peer routers available",Y.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new w("Should not try to find self",Y.ERR_FIND_SELF);let n=await Me(Jt(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){Hz.error(s)}}())),i=>Lr(i,Boolean),i=>Ef(i,this.components.peerStore),async i=>Ns(i));if(n!=null)return n;throw new w(es.NOT_FOUND,Y.ERR_NOT_FOUND)}async*getClosestPeers(e,t){if(this.routers.length===0)throw new w("No peer routers available",Y.ERR_NO_ROUTERS_AVAILABLE);yield*Me(Jt(...this.routers.map(n=>n.getClosestPeers(e,t))),n=>Ef(n,this.components.peerStore),n=>n1(n),n=>i1(n))}};var bg=C("libp2p:registrar"),wg=32,Eg=64,a1=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new w(`No handler registered for protocol ${e}`,Y.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new w(`Handler already registered for protocol ${e}`,Y.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=yo.bind({ignoreUndefined:!0})({maxInboundStreams:wg,maxOutboundStreams:Eg},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let t=Array.isArray(e)?e:[e];t.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:t})}async register(e,t){if(t==null)throw new w("invalid topology",Y.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect?.(t)}}).catch(n=>{n.code!==Y.ERR_NOT_FOUND&&bg.error("could not inform topologies of disconnecting peer %p",t,n)})}_onConnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){bg("peer %p connected but the connection manager did not have a connection",n);return}for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onConnect?.(t,i)}}).catch(n=>{n.code!==Y.ERR_NOT_FOUND&&bg.error("could not inform topologies of connecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!t.protocols.includes(o)),s=t.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect?.(t.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(t.id)[0];u!=null&&c.onConnect?.(t.id,u)}}}};var Ua=C("libp2p:transports"),c1=class{components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=Ki({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Eo.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new w("Transport must have a valid tag",Y.ERR_INVALID_KEY);if(this.transports.has(t))throw new w(`There is already a transport with the tag ${t}`,Y.ERR_DUPLICATE_TRANSPORT);Ua("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(Ua("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Ua("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw new w(`No transport available for address ${String(e)}`,Y.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=Y.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new w("Not started",Y.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){Ua("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){Ua("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(d=>d===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){t.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Eo.NO_FATAL)throw new w(`Transport (${n}) could not listen on any available address`,Y.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Eo.FATAL_ALL)throw new w(n,Y.ERR_NO_VALID_ADDRESSES);Ua(`libp2p in dial mode only: ${n}`)}}async remove(e){Ua("removing %s",e);for(let t of this.listeners.get(e)??[])await t.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var _g=j(Xr(),1);var Os="/multistream/1.0.0";function xg(r){let e=async function*(){let t=yield,n=new Te;for await(let i of r){if(t==null){n.append(i),t=yield n,n=new Te;continue}for(n.append(i);n.length>=t;){let s=n.sublist(0,t);if(n.consume(t),t=yield s,t==null){n.length>0&&(t=yield n,n=new Te);break}}}if(t!=null)throw Object.assign(new Error(`stream ended before ${t} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function u1(r){let e=Pt(),t=xg(r.source),n=Le(),i,s=r.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:t,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:t},rest:()=>e.end(),write:e.push,read:async()=>{let a=await t.next();if(a.value!=null)return a.value}}}var xf=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function _S(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Er(r,e,t){let n=t??{},i=_S(r);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new xf(l,f)}let u=new Promise((l,f)=>{o=()=>{let{abortMessage:h,abortCode:d}=n;f(new xf(h,d))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(r),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function Gz(r,e,t){return n=>r(Er(n,e,t))}function Ri(r,e,t){return{sink:Gz(r.sink,e,{...t,onAbort:void 0}),source:Er(r.source,e,t)}}var Yz=C("libp2p:mss"),SS=G(` `);function vf(r){let e=new Te(r,SS);return Kt.single(e)}function Fa(r,e,t={}){let n=vf(e);t.writeBytes===!0?r.push(n.subarray()):r.push(n)}function RS(r,e,t={}){let n=new Te;for(let i of e)n.append(vf(i));t.writeBytes===!0?r.push(n.subarray()):r.push(n)}async function Qz(r,e){let t=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>r.next(t)},i=n;e?.signal!=null&&(i=Er(n,e.signal));let s=a=>{t=a},o=await Me(i,a=>Yt(a,{onLength:s,maxDataLength:1024}),async a=>Ns(a));if(o==null||o.length===0)throw new w("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==SS[0])throw Yz.error("Invalid mss message - missing newline - %s",o.subarray()),new w("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function su(r,e){let t=await Qz(r,e);return U(t.subarray())}var _f=C("libp2p:mss:select");async function Sf(r,e,t={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=u1(r),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");_f.trace('select: write ["%s", "%s"]',Os,a);let c=G(Os),u=G(a);RS(i,[c,u],t);let l=await su(n,t);if(_f.trace('select: read "%s"',l),l===Os&&(l=await su(n,t),_f.trace('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let f of e){_f.trace('select: write "%s"',f),Fa(i,G(f),t);let h=await su(n,t);if(_f.trace('select: read "%s" for "%s"',h,f),h===f)return s(),{stream:o,protocol:f}}throw s(),new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var Rf=C("libp2p:mss:handle");async function If(r,e,t){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=u1(r);for(;;){let a=await su(i,t);if(Rf.trace('read "%s"',a),a===Os){Rf.trace('respond with "%s" for "%s"',Os,a),Fa(n,G(Os),t);continue}if(e.includes(a))return Fa(n,G(a),t),Rf.trace('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){Fa(n,new Te(...e.map(c=>vf(G(c)))),t),Rf.trace('respond with "%s" for %s',e,a);continue}Fa(n,G("na"),t),Rf('respond with "na" for "%s"',a)}}var TS=j(Xr(),1);var AS=Symbol.for("@libp2p/connection");var l1=C("libp2p:connection"),jz=500,vg=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:i,close:s,abort:o,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this._newStream=i,this._close=s,this._abort=o,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[AS]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new w("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new w("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new w("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){l1("closing connection to %a",this.remoteAddr),this.status="closing",e.signal=e?.signal??AbortSignal.timeout(jz);try{(0,TS.setMaxListeners)?.(1/0,e.signal)}catch{}try{await Promise.all(this.streams.map(async t=>t.close(e))),await this._close(e),this.timeline.close=Date.now(),this.status="closed"}catch(t){l1.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){l1.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),l1.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function DS(r){return new vg(r)}var St=C("libp2p:upgrader");function Jz(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==Y.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return wg}function e$(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==Y.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Eg}function CS(r,e,t){let n=0;return t.streams.forEach(i=>{i.direction===e&&i.protocol===r&&n++}),n}var f1=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,t,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,t))throw new w(`The multiaddr connection is blocked by gater.${n}`,Y.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new w("connection denied",Y.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=er([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,_g.setMaxListeners)?.(1/0,u)}catch{}try{let l=Ri(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new w("The multiaddr connection is blocked by gater.acceptConnection",Y.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),St("starting the inbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(St("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,t?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f));let h={...f,...i};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new w("inbound connection that skipped encryption must have a peer id",Y.ERR_INVALID_MULTIADDR);let d=we(h);c="native",s=d}if(o=i,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,o=h.stream}}catch(h){throw St.error("Failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),St("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=we(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),St("Starting the outbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,t?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...s};await this.shouldBlockConnection(o,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new w("Encryption was skipped but no peer id was passed",Y.ERR_INVALID_PEER);c="native",o=i}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw St.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),St("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a,transient:c}=e,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await If(p,m);if(St("%s: incoming stream opened on %s",n,y),f==null)return;let b=Jz(y,this.components.registrar);if(CS(y,"inbound",f)===b){let _=new w(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`,Y.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(_),_}p.source=g.source,p.sink=g.sink,p.protocol=y,await this.components.peerStore.merge(o,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:y})}).catch(async m=>{St.error(m),p.timeline.close==null&&await p.close()})}}),l=async(p,m={})=>{if(u==null)throw new w("Stream is not multiplexed",Y.ERR_MUXER_UNAVAILABLE);St("%s: starting new stream on %s",n,p);let g=await u.newStream();try{if(m.signal==null){St("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p),m.signal=AbortSignal.timeout(3e4);try{(0,_g.setMaxListeners)?.(1/0,m.signal)}catch{}}let{stream:y,protocol:b}=await Sf(g,p,m),E=e$(b,this.components.registrar,m);if(CS(b,"outbound",f)>=E){let x=new w(`Too many outbound protocol streams for protocol "${b}" - limit ${E}`,Y.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw g.abort(x),x}return await this.components.peerStore.merge(o,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,this.components.metrics?.trackProtocolStream(g,f),g}catch(y){throw St.error("could not create new stream",y),g.timeline.close==null&&g.abort(y),y.code!=null?y:new w(String(y),Y.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{St.error(p)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...p)=>(f!=null&&p[1]==="close"&&p[2]!=null&&h.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){St.error(m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{St.error(m)}),Reflect.set(...p))}),i.timeline.upgraded=Date.now();let d=()=>{throw new w("connection is not multiplexed",Y.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=DS({remoteAddr:i.remoteAddr,remotePeer:o,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:t,transient:c,newStream:l??d,getStreams:()=>u!=null?u.streams:[],close:async p=>{await i.close(p),u!=null&&await u.close(p)},abort:p=>{i.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(e){let{connection:t,stream:n,protocol:i}=e,{handler:s,options:o}=this.components.registrar.getHandler(i);if(t.transient&&o.runOnTransientConnection!==!0)throw new w("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());St("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:i}=await If(e,t,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return St("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new w(String(n),Y.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());St("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await Sf(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return St("encrypting outbound connection to %p",t),{...await o.secureOutbound(this.components.peerId,i,t),protocol:s}}catch(i){throw new w(String(i),Y.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());St("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await Sf(e,n,{writeBytes:!0});St("%s selected as muxer protocol",s);let o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw St.error("error multiplexing outbound stream",i),new w(String(i),Y.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());St("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await If(e,n,{writeBytes:!0}),o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw St.error("error multiplexing inbound stream",i),new w(String(i),Y.ERR_MUXER_UNAVAILABLE)}}};var en=C("libp2p"),Sg=class extends Ye{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let t=new Ye,n=t.dispatchEvent.bind(t);t.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new nt(c.type,{detail:c.detail}));return u||l};try{(0,PS.setMaxListeners)?.(1/0,t)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=i_({peerId:e.peerId,events:t,datastore:e.datastore??new na,connectionGater:p_(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new qd(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{if(c.detail.previous==null){let u={id:c.detail.peer.id,multiaddrs:c.detail.peer.addresses.map(l=>l.multiaddr),protocols:c.detail.peer.protocols};this.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new f1(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new c1(this.components,e.transportManager)),this.configureComponent("connectionManager",new r1(this.components,e.connectionManager)),this.configureComponent("registrar",new a1(this.components)),this.configureComponent("addressManager",new zd(this.components,e.addresses));let s=Oa.generateOptions();this.keychain=this.configureComponent("keyChain",new Oa(this.components,{...s,...e.keychain}));let o=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new o1(this.components,{routers:o}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new s1(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){en.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[cf]!=null&&(en("registering service %s for content routing",c),a.push(l[cf])),l[uf]!=null&&(en("registering service %s for peer routing",c),o.push(l[uf])),l[Ta]!=null&&(en("registering service %s for peer discovery",c),l[Ta].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,t){return t==null&&en.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.#e)return;this.#e=!0,en("libp2p is starting"),(await this.keychain.listKeys()).find(t=>t.name==="self")==null&&(en("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),en("libp2p has started")}catch(t){throw en.error("An error occurred starting libp2p",t),await this.stop(),t}}async stop(){this.#e&&(en("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),en("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Hn;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,t)}async dialProtocol(e,t,n={}){if(t==null)throw new w("no protocols were provided to open a stream",Y.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new w("no protocols were provided to open a stream",Y.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Ba(e)&&(e=we(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(en("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=ve([G("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,t);return vi(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){en.error(new Error(Y.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs,protocols:t.protocols}).catch(n=>{en.error(n)})}};async function kS(r){if(r.peerId==null){let e=r.datastore;if(e!=null)try{let t=new Oa({datastore:e},yo(Oa.generateOptions(),r.keychain));r.peerId=await t.exportPeerId("self")}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}}return r.peerId==null&&(r.peerId=await Cd()),new Sg(__(r))}async function NS(r){let e=await kS(r);return r.start!==!1&&await e.start(),e}var h1=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,n){this.gossip=e,this.msgIdToStrFn=n;for(let i=0;i{let s=this.msgs.get(i.msgIdStr);if(s&&s.validated&&e.has(i.topic)){let o=t.get(i.topic);o||(o=[],t.set(i.topic,o)),o.push(i.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(!t)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:i}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:i}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t?(this.msgs.delete(e),t):null}};var GS=j(HS(),1),{RPC:Df}=GS.default;var Ag="/floodsub/1.0.0",Tg="/meshsub/1.0.0",Dg="/meshsub/1.1.0";var WS="ERR_TOPIC_VALIDATOR_REJECT",YS="ERR_TOPIC_VALIDATOR_IGNORE";function ts(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},i$={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function jS(r={}){return{...n$,...r,topics:r.topics?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=s$(n),e),{}):{}}}function s$(r={}){return{...i$,...r}}function ZS(r){for(let[e,t]of Object.entries(r.topics))try{o$(t)}catch(n){throw new w(`invalid score parameters for topic ${e}: ${n.message}`,ct)}if(r.topicScoreCap<0)throw new w("invalid topic score cap; must be positive (or 0 for no cap)",ct);if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new w("missing application specific score function",ct);if(r.IPColocationFactorWeight>0)throw new w("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",ct);if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new w("invalid IPColocationFactorThreshold; must be at least 1",ct);if(r.behaviourPenaltyWeight>0)throw new w("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",ct);if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new w("invalid BehaviourPenaltyDecay; must be between 0 and 1",ct);if(r.decayInterval<1e3)throw new w("invalid DecayInterval; must be at least 1s",ct);if(r.decayToZero<=0||r.decayToZero>=1)throw new w("invalid DecayToZero; must be between 0 and 1",ct)}function o$(r){if(r.topicWeight<0)throw new w("invalid topic weight; must be >= 0",ct);if(r.timeInMeshQuantum===0)throw new w("invalid TimeInMeshQuantum; must be non zero",ct);if(r.timeInMeshWeight<0)throw new w("invalid TimeInMeshWeight; must be positive (or 0 to disable)",ct);if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new w("invalid TimeInMeshQuantum; must be positive",ct);if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new w("invalid TimeInMeshCap; must be positive",ct);if(r.firstMessageDeliveriesWeight<0)throw new w("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",ct);if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new w("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",ct);if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new w("invalid FirstMessageDeliveriesCap; must be positive",ct);if(r.meshMessageDeliveriesWeight>0)throw new w("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",ct);if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new w("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",ct);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new w("invalid MeshMessageDeliveriesCap; must be positive",ct);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new w("invalid MeshMessageDeliveriesThreshold; must be positive",ct);if(r.meshMessageDeliveriesWindow<0)throw new w("invalid MeshMessageDeliveriesWindow; must be non-negative",ct);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new w("invalid MeshMessageDeliveriesActivation; must be at least 1s",ct);if(r.meshFailurePenaltyWeight>0)throw new w("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",ct);if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new w("invalid MeshFailurePenaltyDecay; must be between 0 and 1",ct);if(r.invalidMessageDeliveriesWeight>0)throw new w("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",ct);if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new w("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",ct)}var a$={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function JS(r={}){return{...a$,...r}}function eR(r,e,t,n){let i=0;Object.entries(e.topics).forEach(([o,a])=>{let c=t.topics[o];if(c===void 0)return;let u=0;if(a.inMesh){let d=a.meshTime/c.timeInMeshQuantum;d>c.timeInMeshCap&&(d=c.timeInMeshCap),u+=d*c.timeInMeshWeight}let l=a.firstMessageDeliveries;if(l>c.firstMessageDeliveriesCap&&(l=c.firstMessageDeliveriesCap),u+=l*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries0&&i>t.topicScoreCap&&(i=t.topicScoreCap);let s=t.appSpecificScore(r);if(i+=s*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=n.get(o),c=a?a.size:0;if(c>t.IPColocationFactorThreshold){let u=c-t.IPColocationFactorThreshold,l=u*u;i+=l*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;i+=a*t.behaviourPenaltyWeight}return i}var nR=j(rR(),1),qr;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(qr||(qr={}));var d1=class{records;queue;constructor(){this.records=new Map,this.queue=new nR.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t)return t;t={status:qr.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t&&t.expire!0){let n=new Set;if(e<=0)return n;for(let i of r){if(n.size>=e)break;t(i)&&(n.add(i),r.delete(i))}return n}function iR(r,e){return m1(r,e,()=>!0)}var p1=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};var au=C("libp2p:gossipsub:score"),g1=class{params;metrics;peerStats=new Map;peerIPs=new p1(()=>new Set);scoreCache=new Map;deliveryRecords=new d1;_backgroundInterval;scoreCacheValidityMs;computeScore;constructor(e,t,n){this.params=e,this.metrics=t,ZS(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??eR}get size(){return this.peerStats.size}start(){if(this._backgroundInterval){au("Peer score already running");return}this._backgroundInterval=setInterval(()=>this.background(),this.params.decayInterval),au("started")}stop(){if(!this._backgroundInterval){au("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),au("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,i)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(i,n.knownIPs),this.peerStats.delete(i),this.scoreCache.delete(i));return}Object.entries(n.topics).forEach(([s,o])=>{let a=this.params.topics[s];a!==void 0&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveriesa.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenaltyn)return i.score;this.metrics?.scoreFnRuns.inc();let s=this.computeScore(e,t,this.params,this.peerIPs),o=n+this.scoreCacheValidityMs;return i?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-i.score)),i.score=s,i.cacheUntil=o):this.scoreCache.set(e,{score:s,cacheUntil:o}),s}addPenalty(e,t,n){let i=this.peerStats.get(e);i&&(i.behaviourPenalty+=t,this.metrics?.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n&&n.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n&&n.knownIPs.delete(t);let i=this.peerIPs.get(t);i&&(i.delete(e),i.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,i])=>{i.firstMessageDeliveries=0;let s=this.params.topics[n].meshMessageDeliveriesThreshold;if(i.inMesh&&i.meshMessageDeliveriesActive&&i.meshMessageDeliveries{o!==e.toString()&&this.markDuplicateMessageDelivery(o,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,i){switch(i){case Vr.Error:this.markInvalidMessageDelivery(e,n);return;case Vr.Blacklisted:return}let s=this.deliveryRecords.ensureRecord(t);if(s.status!==qr.unknown){au("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeenTsMs,qr[s.status]);return}if(i===Vr.Ignore){s.status=qr.ignored,s.peers.clear();return}s.status=qr.invalid,this.markInvalidMessageDelivery(e,n),s.peers.forEach(o=>{this.markInvalidMessageDelivery(o,n)}),s.peers.clear()}duplicateMessage(e,t,n){let i=this.deliveryRecords.ensureRecord(t);if(!i.peers.has(e))switch(i.status){case qr.unknown:i.peers.add(e);break;case qr.valid:i.peers.add(e),this.markDuplicateMessageDelivery(e,n,i.validated);break;case qr.invalid:this.markInvalidMessageDelivery(e,n);break;case qr.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);i&&(i.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);if(i){let s=this.params.topics[t].firstMessageDeliveriesCap;i.firstMessageDeliveries=Math.min(s,i.firstMessageDeliveries+1),i.inMesh&&(s=this.params.topics[t].meshMessageDeliveriesCap,i.meshMessageDeliveries=Math.min(s,i.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){let i=this.peerStats.get(e);if(i){let s=n!==void 0?Date.now():0,o=this.getPtopicStats(i,t);if(o&&o.inMesh){let a=this.params.topics[t];if(n!==void 0){let u=s-n,l=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,l),l)return}let c=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(c,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let i=this.peerIPs.get(n);i&&(i.delete(e),i.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};var y1=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),i=t[n],s=this.msgIdToStrFn(i),o=this.promises.get(s);o||(o=new Map,this.promises.set(s,o));let a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(s)||this.requestMsByMsg.set(s,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,n=0;return this.promises.forEach((i,s)=>{i.forEach((o,a)=>{o=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var sR;(function(r){r.forward="forward",r.publish="publish"})(sR||(sR={}));var Bs;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Bs||(Bs={}));var Va;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Va||(Va={}));var lu;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(lu||(lu={}));var fu;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(fu||(fu={}));var uu;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(uu||(uu={}));function oR(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEvents:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_total",help:"Number of times we include peers in a topic mesh for different reasons",labelNames:["reason"]}),meshPeerInclusionEventsByTopic:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_by_topic_total",help:"Number of times we include peers in a topic",labelNames:["topic"]}),meshPeerChurnEvents:r.gauge({name:"gossipsub_peer_churn_events_total",help:"Number of times we remove peers in a topic mesh for different reasons",labelNames:["reason"]}),meshPeerChurnEventsByTopic:r.gauge({name:"gossipsub_peer_churn_events_by_topic_total",help:"Number of times we remove peers in a topic",labelNames:["topic"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),asyncValidationResult:r.gauge({name:"gossipsub_async_validation_result_total",help:"Message validation result",labelNames:["acceptance"]}),asyncValidationResultByTopic:r.gauge({name:"gossipsub_async_validation_result_by_topic_total",help:"Message validation result for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",labelNames:["topic"],buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),msgPublishPeersByGroup:r.gauge({name:"gossipsub_msg_publish_peers_by_group",help:"Total count of peers (by group) that we publish a msg to",labelNames:["peerGroup"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),msgReceivedStatus:r.gauge({name:"gossipsub_msg_received_status_total",help:"Tracks distribution of recv msgs by duplicate, invalid, valid",labelNames:["status"]}),msgReceivedTopic:r.gauge({name:"gossipsub_msg_received_topic_total",help:"Tracks distribution of recv msgs by topic label",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,1*t.maxMeshMessageDeliveriesWindowSec,2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,1*t.behaviourPenaltyThreshold,2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,1*t.gossipPromiseExpireSec,2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,i,s){let o=this.toTopic(n);this.meshPeerInclusionEvents.inc({reason:i},s),this.meshPeerInclusionEventsByTopic.inc({topic:o},s)},onRemoveFromMesh(n,i,s){let o=this.toTopic(n);this.meshPeerChurnEvents.inc({reason:i},s),this.meshPeerChurnEventsByTopic.inc({topic:o},s)},onReportValidation(n,i,s){if(this.asyncValidationMcacheHit.inc({hit:n!=null?"hit":"miss"}),n!=null){let o=this.toTopic(n.message.topic);this.asyncValidationResult.inc({acceptance:i}),this.asyncValidationResultByTopic.inc({topic:o})}s!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-s)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,i,s){let o=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:o},i),this.ihaveRcvNotSeenMsgids.inc({topic:o},s)},onIwantRcv(n,i){for(let[s,o]of n){let a=this.toTopic(s);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(i)},onForwardMsg(n,i){let s=this.toTopic(n);this.msgForwardCount.inc({topic:s},1),this.msgForwardPeers.inc({topic:s},i)},onPublishMsg(n,i,s,o,a){let c=this.toTopic(n);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},s*o),this.msgPublishPeersByTopic.inc({topic:c},s),this.msgPublishPeersByGroup.inc({peerGroup:"direct"},i.direct),this.msgPublishPeersByGroup.inc({peerGroup:"floodsub"},i.floodsub),this.msgPublishPeersByGroup.inc({peerGroup:"mesh"},i.mesh),this.msgPublishPeersByGroup.inc({peerGroup:"fanout"},i.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(n){let i=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:i},1)},onMsgRecvError(n){let i=this.toTopic(n);this.msgReceivedError.inc({topic:i},1)},onMsgRecvResult(n,i){let s=this.toTopic(n);this.msgReceivedTopic.inc({topic:s}),this.msgReceivedStatus.inc({status:i})},onMsgRecvInvalid(n,i){let s=this.toTopic(n),o=i.reason===Vr.Error?i.error:i.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:s},1)},onDuplicateMsgDelivery(n,i,s){if(this.duplicateMsgDeliveryDelay.observe(i/1e3),s){let o=this.toTopic(n);this.duplicateMsgLateDelivery.inc({topic:o},1)}},onPublishDuplicateMsg(n){let i=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:i},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,i){this.rpcRecvBytes.inc(i),this.rpcRecvCount.inc(1),n.subscriptions&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages&&this.rpcRecvMessage.inc(n.messages.length),n.control&&(this.rpcRecvControl.inc(1),n.control.ihave&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,i){if(this.rpcSentBytes.inc(i),this.rpcSentCount.inc(1),n.subscriptions&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages&&this.rpcSentMessage.inc(n.messages.length),n.control){let s=n.control.ihave?.length??0,o=n.control.iwant?.length??0,a=n.control.graft?.length??0,c=n.control.prune?.length??0;s>0&&this.rpcSentIHave.inc(s),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),(s>0||o>0||a>0||c>0)&&this.rpcSentControl.inc(1)}},registerScores(n,i){let s=0,o=0,a=0,c=0;for(let u of n)u>=i.graylistThreshold&&s++,u>=i.publishThreshold&&o++,u>=i.gossipThreshold&&a++,u>=0&&c++;this.peersByScoreThreshold.set({threshold:uu.graylist},s),this.peersByScoreThreshold.set({threshold:uu.publish},o),this.peersByScoreThreshold.set({threshold:uu.gossip},a),this.peersByScoreThreshold.set({threshold:uu.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[i,s]of n.byTopic)this.scoreWeights.set({topic:i,p:"p1"},s.p1w),this.scoreWeights.set({topic:i,p:"p2"},s.p2w),this.scoreWeights.set({topic:i,p:"p3"},s.p3w),this.scoreWeights.set({topic:i,p:"p3b"},s.p3bw),this.scoreWeights.set({topic:i,p:"p4"},s.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,i){let s=new Map;n.forEach((o,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",u=s.get(c);u||(u=new Set,s.set(c,u)),o.forEach(l=>u?.add(l))});for(let[o,a]of s){let c=[];a.forEach(u=>{c.push(i.get(u)??0)}),this.scorePerMesh.set({topic:o},c)}}}}var aR=G("libp2p-pubsub:");async function cR(r,e,t,n){switch(r.type){case _o.Signing:{let i={from:r.author.toBytes(),data:n,seqno:zn(8),topic:e,signature:void 0,key:void 0},s=ve([aR,Df.Message.encode(i).finish()]);i.signature=await r.privateKey.sign(s),i.key=r.key;let o={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${U(i.seqno,"base16")}`),topic:e,signature:i.signature,key:i.key};return{raw:i,msg:o}}case _o.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}}}}async function uR(r,e){switch(r){case ou:return e.signature!=null?{valid:!1,error:Nr.SignaturePresent}:e.seqno!=null?{valid:!1,error:Nr.SeqnoPresent}:e.key!=null?{valid:!1,error:Nr.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Ka:{if(e.seqno==null)return{valid:!1,error:Nr.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Nr.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Nr.InvalidSignature};if(e.from==null)return{valid:!1,error:Nr.InvalidPeerId};let t;try{t=Ot(e.from)}catch{return{valid:!1,error:Nr.InvalidPeerId}}let n;if(e.key){if(n=vi(e.key),t.publicKey!==void 0&&!fe(n.bytes,t.publicKey))return{valid:!1,error:Nr.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Nr.InvalidPeerId};n=vi(t.publicKey)}let i={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},s=ve([aR,Df.Message.encode(i).finish()]);return await n.verify(s,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${U(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:e.key??af(n)}}:{valid:!1,error:Nr.InvalidSignature}}}}var lR=(r,e)=>{let t=G(e.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),n};function fR(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return lR(r.from.toBytes(),r.sequenceNumber)}async function hR(r){return await Ke.encode(r.data)}function u$(r,e,t,n,i){let s=0,o=new Map;if(Object.entries(e.topics).forEach(([h,d])=>{let p=i.get(h)??"unknown",m=t.topics[h];if(m===void 0)return;let g=o.get(p);g||(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(p,g));let y=0,b=0,E=0,_=0,x=0;if(d.inMesh){let P=Math.max(d.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=P*m.timeInMeshWeight}let v=d.firstMessageDeliveries;if(v>m.firstMessageDeliveriesCap&&(v=m.firstMessageDeliveriesCap),b+=v*m.firstMessageDeliveriesWeight,d.meshMessageDeliveriesActive&&d.meshMessageDeliveries0&&s>t.topicScoreCap){s=t.topicScoreCap;let h=t.topicScoreCap/s;for(let d of o.values())d.p1w*=h,d.p2w*=h,d.p3w*=h,d.p3bw*=h,d.p4w*=h}let a=0,c=0,u=0,l=t.appSpecificScore(r);a+=l*t.appSpecificWeight,e.knownIPs.forEach(h=>{if(t.IPColocationFactorWhitelist.has(h))return;let d=n.get(h),p=d?d.size:0;if(p>t.IPColocationFactorThreshold){let m=p-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let f=e.behaviourPenalty*e.behaviourPenalty;return u+=f*t.behaviourPenaltyWeight,s+=a+c+u,{byTopic:o,p5w:a,p6w:c,p7w:u,score:s}}function dR(r,e,t,n,i){let s={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of r){let a=e.get(o);if(a){let c=u$(o,a,t,n,i);for(let[u,l]of c.byTopic){let f=s.byTopic.get(u);f||(f={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},s.byTopic.set(u,f)),f.p1w.push(l.p1w),f.p2w.push(l.p2w),f.p3w.push(l.p3w),f.p3bw.push(l.p3bw),f.p4w.push(l.p4w)}s.p5w.push(c.p5w),s.p6w.push(c.p6w),s.p7w.push(c.p7w),s.score.push(c.score)}else s.p5w.push(0),s.p6w.push(0),s.p7w.push(0),s.score.push(0)}return s}var b1=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,n){this.rawStream=e,this.pushable=Pt({objectMode:!1}),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,Me(Er(this.pushable,this.closeController.signal,{returnOnAbort:!0}),i=>Kt(i),this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}close(){this.closeController.abort(),this.pushable.return(),this.rawStream.close()}},w1=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.source=Er(Me(this.rawStream,n=>Yt(n,t)),this.closeController.signal,{returnOnAbort:!0})}close(){this.closeController.abort(),this.rawStream.close()}};var pR=j(Ig(),1),mR={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};function gR(r,e){e={...e};let t=pR.default.Reader.create(r),n=r.length,i=n===void 0?t.len:t.pos+n,s={};for(;t.pos>>3){case 1:s.subscriptions&&s.subscriptions.length||(s.subscriptions=[]),s.subscriptions.length>>3){case 1:n.subscribe=r.bool();break;case 2:n.topic=r.string();break;default:r.skipType(i&7);break}}return n}function f$(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.from=r.bytes();break;case 2:n.data=r.bytes();break;case 3:n.seqno=r.bytes();break;case 4:n.topic=r.string();break;case 5:n.signature=r.bytes();break;case 6:n.key=r.bytes();break;default:r.skipType(i&7);break}}if(!n.topic)throw Error("missing required 'topic'");return n}function h$(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.ihave&&i.ihave.length||(i.ihave=[]),i.ihave.length>>3){case 1:i.topicID=r.string();break;case 2:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIhaveMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(s&7);break;default:r.skipType(s&7);break}}return i}function p$(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIwantMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(s&7);break;default:r.skipType(s&7);break}}return i}function m$(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.topicID=r.string();break;default:r.skipType(i&7);break}}return n}function g$(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos>>3){case 1:i.topicID=r.string();break;case 2:i.peers&&i.peers.length||(i.peers=[]),t.maxPeerInfos-- >0?i.peers.push(y$(r,r.uint32())):r.skipType(s&7);break;case 3:i.backoff=r.uint64();break;default:r.skipType(s&7);break}}return i}function y$(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos>>3){case 1:n.peerID=r.bytes();break;case 2:n.signedPeerRecord=r.bytes();break;default:r.skipType(i&7);break}}return n}var E1;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(E1||(E1={}));function yR(r){for(let e of r.tuples())switch(e[0]){case E1.ip4:case E1.ip6:return mf(e[0],e[1])}return null}var En;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(En||(En={}));var kg=class extends Ye{globalSignaturePolicy;multicodecs=[Dg,Tg];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Pt({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;components;directPeerInitial=null;static multicodec=Dg;opts;decodeRpcLimits;metrics;status={code:En.stopped};maxInboundStreams;maxOutboundStreams;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let n={fallbackToFloodsub:!0,floodPublish:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,...t,scoreParams:jS(t.scoreParams),scoreThresholds:JS(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??mR,this.globalSignaturePolicy=n.globalSignaturePolicy??Ka,n.fallbackToFloodsub&&this.multicodecs.push(Ag),this.log=C(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map(i=>i.id.toString())),this.seenCache=new cu({validityMs:n.seenTTL}),this.publishedMessageIds=new cu({validityMs:n.seenTTL}),t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Ka:this.msgIdFn=fR;break;case ou:this.msgIdFn=hR;break}if(t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new cu({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??QS,this.mcache=t.messageCache||new h1(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform&&(this.dataTransform=t.dataTransform),t.metricsRegister){if(!t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");let i=Math.max(...Object.values(n.scoreParams.topics).map(o=>o.meshMessageDeliveriesWindow),1e3),s=oR(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:i/1e3});s.mcacheSize.addCollect(()=>this.onScrapeMetrics(s));for(let o of this.multicodecs)s.protocolsEnabled.set({protocol:o},1);this.metrics=s}else this.metrics=null;this.gossipTracer=new y1(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new g1(this.opts.scoreParams,this.metrics,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.allowedTopics=n.allowedTopics?new Set(n.allowedTopics):null}getPeers(){return[...this.peers.keys()].map(e=>we(e))}isStarted(){return this.status.code===En.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await Pg(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=Pt({objectMode:!0}),Me(this.outboundInflightQueue,async s=>{for await(let{peerId:o,connection:a}of s)await this.createOutboundStream(o,a)}).catch(s=>this.log.error("outbound inflight queue error",s)),await Promise.all(this.opts.directPeers.map(async s=>{await this.components.peerStore.merge(s.id,{multiaddrs:s.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(s=>e.handle(s,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this)},n=await Promise.all(this.multicodecs.map(s=>e.register(s,t))),i=setTimeout(this.runHeartbeat,100);this.status={code:En.started,registrarTopologyIds:n,heartbeatTimeout:i,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async s=>await this.connect(s)))}).catch(s=>{this.log(s)})},1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==En.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:En.stopped};let t=this.components.registrar;await Promise.all(this.multicodecs.map(n=>t.unhandle(n))),e.forEach(n=>t.unregister(n)),this.outboundInflightQueue.end();for(let n of this.streamsOutbound.values())n.close();this.streamsOutbound.clear();for(let n of this.streamsInbound.values())n.close();this.streamsInbound.clear(),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache&&this.fastMsgIdCache.clear(),this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let i=new b1(await t.newStream(this.multicodecs),o=>this.log.error("outbound pipe error",o),{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,i);let s=i.protocol;s===Ag&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:s},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(i){this.log.error("createOutboundStream error",i)}}async createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let i=this.streamsInbound.get(n);i!==void 0&&(this.log("replacing existing inbound steam %s",n),i.close()),this.log("create inbound stream %s",n);let s=new w1(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,s),this.pipePeerReadStream(e,s.source).catch(o=>this.log(o))}addPeer(e,t,n){let i=e.toString();if(!this.peers.has(i)){this.log("new peer %p",e),this.peers.add(i),this.score.addPeer(i);let s=yR(n);s!==null?this.score.addIP(i,s):this.log("Added peer has no IP in current address %s %s",i,n.toString()),this.outbound.has(i)||this.outbound.set(i,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),i=this.streamsInbound.get(t);n&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close(),i?.close(),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let s of this.topics.values())s.delete(t);for(let[s,o]of this.mesh)o.delete(t)===!0&&this.metrics?.onRemoveFromMesh(s,Va.Dc,1);for(let s of this.fanout.values())s.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===En.started}getMeshPeers(e){let t=this.mesh.get(e);return t?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t?Array.from(t):[]).map(n=>we(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await Me(t,async n=>{for await(let i of n)try{let s=i.subarray(),o=gR(s,this.decodeRpcLimits);if(this.metrics?.onRpcRecv(o,s.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(s){this.metrics?.onRpcDataError(),this.log(s)}})}catch(n){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(n,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let n=t.subscriptions?t.subscriptions.length:0,i=t.messages?t.messages.length:0,s=0,o=0,a=0,c=0;if(t.control&&(t.control.ihave&&(s=t.control.ihave.length),t.control.iwant&&(o=t.control.iwant.length),t.control.graft&&(a=t.control.graft.length),t.control.prune&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${i} ihave ${s} iwant ${o} graft ${a} prune ${c}`),t.subscriptions&&t.subscriptions.length>0){let u=[];t.subscriptions.forEach(l=>{let f=l.topic,h=l.subscribe===!0;if(f!=null){if(this.allowedTopics&&!this.allowedTopics.has(f))return;this.handleReceivedSubscription(e,f,h),u.push({topic:f,subscribe:h})}}),this.dispatchEvent(new nt("subscription-change",{detail:{peerId:e,subscriptions:u}}))}if(t.messages)for(let u of t.messages){if(this.allowedTopics&&!this.allowedTopics.has(u.topic))continue;let l=this.handleReceivedMessage(e,u).catch(f=>{this.metrics?.onMsgRecvError(u.topic),this.log(f)});this.opts.awaitRpcMessageHandler&&await l}t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let i=this.topics.get(t);i==null&&(i=new Set,this.topics.set(t,i)),n?i.add(e.toString()):i.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);switch(this.metrics?.onMsgRecvResult(t.topic,n.code),n.code){case Yn.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case Yn.invalid:if(n.msgIdStr){let i=n.msgIdStr;this.score.rejectMessage(e.toString(),i,t.topic,n.reason),this.gossipTracer.rejectMessage(i,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,n);return;case Yn.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new nt("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new nt("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString())}}async validateReceivedMessage(e,t){let n=this.fastMsgIdFn?.(t),i=n!==void 0?this.fastMsgIdCache?.get(n):void 0;if(i)return{code:Yn.duplicate,msgIdStr:i};let s=await uR(this.globalSignaturePolicy,t);if(!s.valid)return{code:Yn.invalid,reason:Vr.Error,error:s.error};let o=s.message;try{this.dataTransform&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(f){return this.log("Invalid message, transform failed",f),{code:Yn.invalid,reason:Vr.Error,error:Nr.TransformFailed}}let a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache&&this.fastMsgIdCache.put(n,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:Yn.duplicate,msgIdStr:c};this.seenCache.put(c);let l=this.topicValidators.get(t.topic);if(l!=null){let f;try{f=await l(e,o)}catch(h){let d=h.code;d===YS&&(f=Ii.Ignore),d===WS?f=Ii.Reject:f=Ii.Ignore}if(f!==Ii.Accept)return{code:Yn.invalid,reason:Cg(f),msgIdStr:c}}return{code:Yn.valid,messageId:u,msg:o}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(i=>({topic:i,subscribe:n}))})}async handleControlMessage(e,t){if(t===void 0)return;let n=t.ihave?this.handleIHave(e,t.ihave):[],i=t.iwant?this.handleIWant(e,t.iwant):[],s=t.graft?await this.handleGraft(e,t.graft):[];if(t.prune&&await this.handlePrune(e,t.prune),!n.length&&!i.length&&!s.length)return;let o=this.sendRpc(e,{messages:i,control:{iwant:n,prune:s}}),a=n[0]?.messageIDs;a&&(o?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let i=this.score.score(e);return i>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),i>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(!t.length)return[];let n=this.score.score(e);if(n10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:fu.MaxIhave}),[];let s=this.iasked.get(e)??0;if(s>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:fu.MaxIasked}),[];let o=new Map;if(t.forEach(({topicID:u,messageIDs:l})=>{if(!u||!l||!this.mesh.has(u))return;let f=0;l.forEach(h=>{let d=this.msgIdToStrFn(h);this.seenCache.has(d)||(o.set(d,h),f++)}),this.metrics?.onIhaveRcv(u,l.length,f)}),!o.size)return[];let a=o.size;a+s>5e3&&(a=5e3-s),this.log("IHAVE: Asking for %d out of %d messages from %s",a,o.size,e);let c=Array.from(o.values());return ts(c),c=c.slice(0,a),this.iasked.set(e,s+a),[{messageIDs:c}]}handleIWant(e,t){if(!t.length)return[];let n=this.score.score(e);if(n{a&&a.forEach(c=>{let u=this.msgIdToStrFn(c),l=this.mcache.getWithIWantCount(u,e);if(l==null){o++;return}if(s.set(l.msg.topic,1+(s.get(l.msg.topic)??0)),l.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}i.set(u,l.msg)})}),this.metrics?.onIwantRcv(s,o),i.size?(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values())):(this.log("IWANT: Could not provide any wanted messages to %s",e),[])}async handleGraft(e,t){let n=[],i=this.score.score(e),s=Date.now(),o=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(!c)return;let u=this.mesh.get(c);if(!u){o=!1;return}if(u.has(e))return;if(this.direct.has(e)){this.log("GRAFT: ignoring request from direct peer %s",e),n.push(c),o=!1;return}let l=this.backoff.get(c)?.get(e);if(typeof l=="number"&&s=this.opts.Dhi&&!this.outbound.get(e)){n.push(c),this.addBackoff(e,c);return}this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),u.add(e),this.metrics?.onAddToMesh(c,Bs.Subscribed,1)}),!n.length)return[];let a=!1;return await Promise.all(n.map(c=>this.makePrune(e,c,o,a)))}async handlePrune(e,t){let n=this.score.score(e);for(let{topicID:i,backoff:s,peers:o}of t){if(i==null)continue;let a=this.mesh.get(i);if(!a)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,i),this.score.prune(e,i),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(i,Va.Prune,1)),typeof s=="number"&&s>0?this.doAddBackoff(e,i,s*1e3):this.addBackoff(e,i),o&&o.length){if(n{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,lu.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((i,s)=>{i+1*this.opts.heartbeatInterval{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>await this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(ts(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(!n.peerID)return;let i=Ot(n.peerID),s=i.toString();if(!this.peers.has(s)){if(!n.signedPeerRecord){t.push(s);return}try{if(!await this.components.peerStore.consumePeerRecord(n.signedPeerRecord,i)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(s)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length&&await Promise.all(t.map(async n=>await this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=we(e),n=await this.components.connectionManager.openConnection(t);for(let i of this.multicodecs)for(let s of this.components.registrar.getTopologies(i))s.onConnect?.(t,n)}subscribe(e){if(this.status.code!==En.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==En.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){if(this.status.code!==En.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,n=this.backoff.get(e),i=this.fanout.get(e);if(i&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),i.forEach(s=>{!this.direct.has(s)&&this.score.score(s)>=0&&(!n||!n.has(s))&&t.add(s)}),this.metrics?.onAddToMesh(e,Bs.Fanout,t.size)),t.size!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&(!n||!n.has(a))).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Bs.Random,t.size-s)}this.mesh.set(e,t),t.forEach(s=>{this.log("JOIN: Add mesh link to %s in %s",s,e),this.sendGraft(s,e)})}leave(e){if(this.status.code!==En.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t&&(Promise.all(Array.from(t).map(async n=>(this.log("LEAVE: Remove mesh link to %s in %s",n,e),await this.sendPrune(n,e)))).catch(n=>{this.log("Error sending prunes to mesh peers",n)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let i=new Set,s=this.topics.get(e);s&&(this.direct.forEach(a=>{s.has(a)&&t!==a&&!n?.has(a)&&i.add(a)}),this.floodsubPeers.forEach(a=>{s.has(a)&&t!==a&&!n?.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&i.add(a)}));let o=this.mesh.get(e);return o&&o.size>0&&o.forEach(a=>{t!==a&&!n?.has(a)&&i.add(a)}),i}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},i=this.topics.get(e);if(i)if(this.opts.floodPublish)i.forEach(s=>{this.direct.has(s)?(t.add(s),n.direct++):this.score.score(s)>=this.opts.scoreThresholds.publishThreshold&&(t.add(s),n.floodsub++)});else{this.direct.forEach(o=>{i.has(o)&&(t.add(o),n.direct++)}),this.floodsubPeers.forEach(o=>{i.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});let s=this.mesh.get(e);if(s&&s.size>0)s.forEach(o=>{t.add(o),n.mesh++});else{let o=this.fanout.get(e);if(o&&o.size>0)o.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,i){n&&this.score.deliverMessage(n,e,t.topic);let s=this.selectPeersToForward(t.topic,n,i);s.forEach(o=>{this.sendRpc(o,{messages:[t]})}),this.metrics?.onForwardMsg(t.topic,s.size)}async publish(e,t,n){let i=Date.now(),s=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:o,msg:a}=await cR(this.publishConfig,e,t,s),c=await this.msgIdFn(a),u=this.msgIdToStrFn(c),l=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(l)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:f,tosendCount:h}=this.selectPeersToPublish(e),d=this.opts.emitSelf===!0&&this.subscriptions.has(e),p=n?.allowPublishToZeroPeers??this.opts.allowPublishToZeroPeers;if(f.size===0&&!p&&!d)throw Error("PublishError.InsufficientPeers");this.seenCache.put(u),this.mcache.put({msgId:c,msgIdStr:u},o,!0),this.publishedMessageIds.put(u);for(let g of f)this.sendRpc(g,{messages:[o]})||f.delete(g);let m=Date.now()-i;return this.metrics?.onPublishMsg(e,h,f.size,o.data!=null?o.data.length:0,m),d&&(f.add(this.components.peerId.toString()),super.dispatchEvent(new nt("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:u,msg:a}})),super.dispatchEvent(new nt("message",{detail:a}))),{recipients:Array.from(f.values()).map(g=>we(g))}}reportMessageValidationResult(e,t,n){let i;if(n===Ii.Accept){if(i=this.mcache.validate(e),i!=null){let{message:o,originatingPeers:a}=i;this.score.deliverMessage(t,e,o.topic),this.forwardMessage(e,i.message,t,a)}}else if(i=this.mcache.remove(e),i){let o=Cg(n),{message:a,originatingPeers:c}=i;this.score.rejectMessage(t,e,a.topic,o);for(let u of c)this.score.rejectMessage(u,e,a.topic,o)}let s=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(i,n,s)}sendGraft(e,t){let n=[{topicID:t}];this.sendRpc(e,{control:{graft:n}})}async sendPrune(e,t){let i=[await this.makePrune(e,t,this.opts.doPX,!0)];this.sendRpc(e,{control:{prune:i}})}sendRpc(e,t){let n=this.streamsOutbound.get(e);if(!n)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let i=this.control.get(e);i&&(this.piggybackControl(e,t,i),this.control.delete(e));let s=this.gossip.get(e);s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));let o=Df.encode(t).finish();try{n.push(o)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),i&&this.control.set(e,i),s&&this.gossip.set(e,s),!1}return this.metrics?.onRpcSent(t,o.length),!0}piggybackControl(e,t,n){if(n.graft){t.control||(t.control={}),t.control.graft||(t.control.graft=[]);for(let i of n.graft)i.topicID&&this.mesh.get(i.topicID)?.has(e)&&t.control.graft.push(i)}if(n.prune){t.control||(t.control={}),t.control.prune||(t.control.prune=[]);for(let i of n.prune)i.topicID&&!this.mesh.get(i.topicID)?.has(e)&&t.control.prune.push(i)}}piggybackGossip(e,t,n){t.control||(t.control={}),t.control.ihave=n}async sendGraftPrune(e,t,n){let i=this.opts.doPX,s=!1;for(let[o,a]of e){let c=a.map(f=>({topicID:f})),u=[],l=t.get(o);l&&(u=await Promise.all(l.map(async f=>await this.makePrune(o,f,i&&!(n.get(o)??!1),s))),t.delete(o)),this.sendRpc(o,{control:{graft:c,prune:u}})}for(let[o,a]of t){let c=await Promise.all(a.map(async u=>await this.makePrune(o,u,i&&!(n.get(o)??!1),s)));this.sendRpc(o,{control:{prune:c}})}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,i]of e)this.doEmitGossip(n,i,t.get(n)??[])}doEmitGossip(e,t,n){if(!n.length||(ts(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),!t.size))return;let i=this.opts.Dlazy,s=.25*t.size,o=t;s>i&&(i=s),i>o.size?i=o.size:o=ts(Array.from(o)).slice(0,i),o.forEach(a=>{let c=n;n.length>5e3&&(c=ts(c.slice()).slice(0,5e3)),this.pushGossip(a,{topicID:e,messageIDs:c})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,{control:{ihave:t}});for(let[e,t]of this.control.entries())this.control.delete(e),this.sendRpc(e,{control:{graft:t.graft,prune:t.prune}})}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)||[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n,i){if(this.score.prune(e,t),this.streamsOutbound.get(e).protocol===Tg)return{topicID:t,peers:[]};let s=i?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,o=s/1e3;if(this.doAddBackoff(e,t,s),!n)return{topicID:t,peers:[],backoff:o};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),c=await Promise.all(Array.from(a).map(async u=>{let l=we(u),f;try{f=await this.components.peerStore.get(l)}catch(h){if(h.code!=="ERR_NOT_FOUND")throw h}return{peerID:l.toBytes(),signedPeerRecord:f?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===En.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t{let m=a.get(p);return m===void 0&&(m=this.score.score(p),a.set(p,m)),m},u=new Map,l=new Map,f=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let h=new Map;this.mesh.forEach((p,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(h.set(m,b),g){let x=ts(Array.from(g)),v=this.backoff.get(m);for(let R of x){let T=this.streamsOutbound.get(R);if(T&&this.multicodecs.includes(T.protocol)&&!p.has(R)&&!this.direct.has(R)){let P=c(R);(!v||!v.has(R))&&P>=0&&y.add(R),P>=this.opts.scoreThresholds.gossipThreshold&&b.add(R)}}}let E=(x,v)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",x,m),this.addBackoff(x,m),p.delete(x),c(x)>=this.opts.scoreThresholds.gossipThreshold&&b.add(x),this.metrics?.onRemoveFromMesh(m,v,1);let R=l.get(x);R?R.push(m):l.set(x,[m])},_=(x,v)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",x,m),this.score.graft(x,m),p.add(x),b.delete(x),this.metrics?.onAddToMesh(m,v,1);let R=u.get(x);R?R.push(m):u.set(x,[m])};if(p.forEach(x=>{let v=c(x);v<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",x,v,m),E(x,Va.BadScore),f.set(x,!0))}),p.size{_(R,Bs.NotEnough)})}if(p.size>n){let x=Array.from(p);x.sort((R,T)=>c(T)-c(R)),x=x.slice(0,i).concat(ts(x.slice(i)));let v=0;if(x.slice(0,e).forEach(R=>{this.outbound.get(R)&&v++}),v{let q=x[P];for(let $=P;$>0;$--)x[$]=x[$-1];x[0]=q};if(v>0){let P=v;for(let q=1;q0;q++)this.outbound.get(x[q])&&(R(q),P--)}let T=e-v;for(let P=e;P0;P++)this.outbound.get(x[P])&&(R(P),T--)}x.slice(e).forEach(R=>{E(R,Va.Excess)})}if(p.size>=t){let x=0;if(p.forEach(v=>{this.outbound.get(v)&&x++}),xthis.outbound.get(T)===!0).forEach(T=>{_(T,Bs.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&p.size>1){let x=Array.from(p).sort((T,P)=>c(T)-c(P)),v=Math.floor(p.size/2),R=c(x[v]);if(Rc(q)>R);for(let q of P)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",q,m),_(q,Bs.Opportunistic)}}});let d=Date.now();this.fanoutLastpub.forEach((p,m)=>{p+o{let g=this.topics.get(m);p.forEach(_=>{(!g.has(_)||c(_)=this.opts.scoreThresholds.publishThreshold&&b.push(x),R>=this.opts.scoreThresholds.gossipThreshold&&E.add(x)}}}if(p.size{p.add(x),E?.delete(x)})}}),this.emitGossip(h),await this.sendGraftPrune(u,l,f),this.flush(),this.mcache.shift(),this.dispatchEvent(new nt("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let i=this.topics.get(e);if(!i)return new Set;let s=[];return i.forEach(o=>{let a=this.streamsOutbound.get(o);a&&this.multicodecs.includes(a.protocol)&&n(o)&&s.push(o)}),s=ts(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,n=Date.now();e.connectedPeersBackoffSec.reset();for(let a of this.backoff.values()){t+=a.size;for(let[c,u]of a.entries())this.peers.has(c)&&e.connectedPeersBackoffSec.observe(Math.max(0,u-n)/1e3)}e.cacheSize.set({cache:"backoff"},t);for(let[a,c]of this.topics)e.topicPeersCount.set({topicStr:a},c.size);for(let[a,c]of this.mesh)e.meshPeerCounts.set({topicStr:a},c.size);let i=[],s=new Map;e.behaviourPenalty.reset();for(let a of this.peers.keys()){let c=this.score.score(a);i.push(c),s.set(a,c),e.behaviourPenalty.observe(this.score.peerStats.get(a)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,s);let o=dR(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(o)}};function wR(r={}){return e=>new kg(e,r)}var x1=class extends Error{code;constructor(e,t){super(e),this.code=t}},Ng=class extends x1{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function ER(r){let e=Pt();r.sink(e).catch(s=>{e.end(s)}),r.sink=async s=>{for await(let o of s)e.push(o);e.end()};let t=r.source;r.source[Symbol.iterator]!=null?t=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(t=r.source[Symbol.asyncIterator]());let n=new Te;return{read:async(s,o)=>{o?.signal?.throwIfAborted();let a,c=new Promise((u,l)=>{a=()=>{l(new Ng("Read aborted"))},o?.signal?.addEventListener("abort",a)});try{if(s==null){let{done:l,value:f}=await Promise.race([t.next(),c]);return l===!0?new Te:f}for(;n.byteLength{o?.signal?.throwIfAborted(),s instanceof Uint8Array?e.push(s):e.push(s.subarray()),await e.onEmpty(o)},unwrap:()=>{let s=r.source;return r.source=async function*(){yield*n,yield*s}(),r}}}var v1=class extends Error{code;constructor(e,t){super(e),this.code=t}},xR=r=>on(r);xR.bytes=0;function Cf(r,e){let t=ER(r);return{read:async i=>{let s=-1,o=new Te,a=e?.lengthDecoder??xR;for(;;){o.append(await t.read(1,i));try{s=a(o)}catch(c){if(c instanceof RangeError)continue;throw c}if(s>-1)break;if(e?.maxLengthLength!=null&&o.byteLength>e.maxLengthLength)throw new v1("message length length too long","ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new v1("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(s,i)},write:async(i,s)=>{await t.write(Kt.single(i,e),s)},unwrap:()=>t.unwrap()}}function Og(){let r=Le(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:async function*(){yield*await r.promise}()}}function vR(){let r=Og(),e=Og();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}var _R=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var W$=r=>r instanceof Uint8Array;var Qn=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),SR=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Y$=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Y$)throw new Error("Non little-endian hardware is not supported");function _1(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function S1(r){if(typeof r=="string"&&(r=_1(r)),!W$(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}var Q$=r=>Object.prototype.toString.call(r)==="[object Object]"&&r.constructor===Object;function RR(r,e){if(e!==void 0&&(typeof e!="object"||!Q$(e)))throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Pf(r,e){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");if(typeof e=="number"&&r.length!==e)throw new Error(`Uint8Array length ${e} expected`)}function IR(r,e){if(r.length!==e.length)throw new Error("equalBytes: Different size of Uint8Arrays");let t=!0;for(let n=0;n>i&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+u,a,n)}function Lg(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function X$(r){if(typeof r!="boolean")throw new Error(`Expected boolean, not ${r}`)}function AR(r,...e){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function j$(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Lg(r.outputLen),Lg(r.blockLen)}function Z$(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function J$(r,e){AR(r);let t=e.outputLen;if(r.lengthr[e++]&255|(r[e++]&255)<<8,Mg=class{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,e=S1(e),Pf(e,32);let t=xr(e,0),n=xr(e,2),i=xr(e,4),s=xr(e,6),o=xr(e,8),a=xr(e,10),c=xr(e,12),u=xr(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=xr(e,16+2*l)}process(e,t,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],f=o[4],h=o[5],d=o[6],p=o[7],m=o[8],g=o[9],y=xr(e,t+0),b=xr(e,t+2),E=xr(e,t+4),_=xr(e,t+6),x=xr(e,t+8),v=xr(e,t+10),R=xr(e,t+12),T=xr(e,t+14),P=s[0]+(y&8191),q=s[1]+((y>>>13|b<<3)&8191),$=s[2]+((b>>>10|E<<6)&8191),Q=s[3]+((E>>>7|_<<9)&8191),te=s[4]+((_>>>4|x<<12)&8191),_e=s[5]+(x>>>1&8191),k=s[6]+((x>>>14|v<<2)&8191),F=s[7]+((v>>>11|R<<5)&8191),O=s[8]+((R>>>8|T<<8)&8191),M=s[9]+(T>>>5|i),A=0,H=A+P*a+q*(5*g)+$*(5*m)+Q*(5*p)+te*(5*d);A=H>>>13,H&=8191,H+=_e*(5*h)+k*(5*f)+F*(5*l)+O*(5*u)+M*(5*c),A+=H>>>13,H&=8191;let X=A+P*c+q*a+$*(5*g)+Q*(5*m)+te*(5*p);A=X>>>13,X&=8191,X+=_e*(5*d)+k*(5*h)+F*(5*f)+O*(5*l)+M*(5*u),A+=X>>>13,X&=8191;let re=A+P*u+q*c+$*a+Q*(5*g)+te*(5*m);A=re>>>13,re&=8191,re+=_e*(5*p)+k*(5*d)+F*(5*h)+O*(5*f)+M*(5*l),A+=re>>>13,re&=8191;let xe=A+P*l+q*u+$*c+Q*a+te*(5*g);A=xe>>>13,xe&=8191,xe+=_e*(5*m)+k*(5*p)+F*(5*d)+O*(5*h)+M*(5*f),A+=xe>>>13,xe&=8191;let Se=A+P*f+q*l+$*u+Q*c+te*a;A=Se>>>13,Se&=8191,Se+=_e*(5*g)+k*(5*m)+F*(5*p)+O*(5*d)+M*(5*h),A+=Se>>>13,Se&=8191;let Be=A+P*h+q*f+$*l+Q*u+te*c;A=Be>>>13,Be&=8191,Be+=_e*a+k*(5*g)+F*(5*m)+O*(5*p)+M*(5*d),A+=Be>>>13,Be&=8191;let Ae=A+P*d+q*h+$*f+Q*l+te*u;A=Ae>>>13,Ae&=8191,Ae+=_e*c+k*a+F*(5*g)+O*(5*m)+M*(5*p),A+=Ae>>>13,Ae&=8191;let Ce=A+P*p+q*d+$*h+Q*f+te*l;A=Ce>>>13,Ce&=8191,Ce+=_e*u+k*c+F*a+O*(5*g)+M*(5*m),A+=Ce>>>13,Ce&=8191;let lt=A+P*m+q*p+$*d+Q*h+te*f;A=lt>>>13,lt&=8191,lt+=_e*l+k*u+F*c+O*a+M*(5*g),A+=lt>>>13,lt&=8191;let it=A+P*g+q*m+$*p+Q*d+te*h;A=it>>>13,it&=8191,it+=_e*f+k*l+F*u+O*c+M*a,A+=it>>>13,it&=8191,A=(A<<2)+A|0,A=A+H|0,H=A&8191,A=A>>>13,X+=A,s[0]=H,s[1]=X,s[2]=re,s[3]=xe,s[4]=Se,s[5]=Be,s[6]=Ae,s[7]=Ce,s[8]=lt,s[9]=it}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535}update(e){zr.exists(this);let{buffer:t,blockLen:n}=this;e=S1(e);let i=e.length;for(let s=0;s>>0,e[s++]=n[o]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function tH(r){let e=(n,i)=>r(i).update(S1(n)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var TR=tH(r=>new Mg(r));var rH=_1("expand 16-byte k"),nH=_1("expand 32-byte k"),iH=Qn(rH),sH=Qn(nH),DR=r=>!(r.byteOffset%4),du=r=>{let{core:e,rounds:t,counterRight:n,counterLen:i,allow128bitKeys:s,extendNonceFn:o,blockLen:a}=RR({rounds:20,counterRight:!1,counterLen:8,allow128bitKeys:!0,blockLen:64},r);zr.number(i),zr.number(t),zr.number(a),zr.bool(n),zr.bool(s);let c=a/4;if(a%4!==0)throw new Error("Salsa/ChaCha: blockLen should be aligned to 4 bytes");return(u,l,f,h,d=0)=>{if(zr.bytes(u),zr.bytes(l),zr.bytes(f),h||(h=new Uint8Array(f.length)),zr.bytes(h),zr.number(d),d<0||d>=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");if(h.length=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");let $=Math.min(a,T-P);if($===a&&R&&v){let Q=P/4;if(P%4!==0)throw new Error("Salsa/ChaCha: wrong block position");for(let te=0;ter<>>32-e;function kf(r,e,t,n,i,s=20){let o=r[0],a=r[1],c=r[2],u=r[3],l=e[0],f=e[1],h=e[2],d=e[3],p=e[4],m=e[5],g=e[6],y=e[7],b=i,E=t[0],_=t[1],x=t[2],v=o,R=a,T=c,P=u,q=l,$=f,Q=h,te=d,_e=p,k=m,F=g,O=y,M=b,A=E,H=_,X=x;for(let xe=0;xe{r.update(e);let t=e.length%16;t&&r.update(uH.subarray(t))},PR=(r,e,t,n,i)=>{let s=r(e,t,new Uint8Array(32)),o=TR.create(s);i&&CR(o,i),CR(o,n);let a=new Uint8Array(16),c=SR(a);Bg(c,0,BigInt(i?i.length:0),!0),Bg(c,8,BigInt(n.length),!0),o.update(a);let u=o.digest();return s.fill(0),u},kR=r=>(e,t,n)=>(Pf(e,32),Pf(t),{tagLength:16,encrypt:s=>{let o=new Uint8Array(s.length+16);r(e,t,s,o,1);let a=PR(r,e,t,o.subarray(0,-16),n);return o.set(a,s.length),o},decrypt:s=>{if(s.length<16)throw new Error("Encrypted data should be at least 16");let o=s.subarray(-16),a=s.subarray(0,-16),c=PR(r,e,t,a,n);if(!IR(o,c))throw new Error("Wrong tag");return r(e,t,a,void 0,1)}}),Ug=kR(aH),cge=kR(cH);function OR(r,e,t){return dn.hash(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Kc(r,uo(t),uo(e))}var Fg=new Uint8Array([0]),NR=new Uint8Array;function BR(r,e,t,n=32){if(dn.hash(r),dn.number(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let i=Math.ceil(n/r.outputLen);t===void 0&&(t=NR);let s=new Uint8Array(i*r.outputLen),o=Kc.create(r,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;uglobalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),pu=r=>{let e=lH(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};pu.bytes=2;var Nf=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");return r instanceof Uint8Array?new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,!1):r.getUint16(0)};Nf.bytes=2;function LR(r){return ve([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function MR(r){return ve([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function UR(r){return ve([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function FR(r){if(r.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:r.subarray(0,32),ciphertext:r.subarray(32,r.length),ns:new Uint8Array(0)}}function KR(r){if(r.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:r.subarray(0,32),ns:r.subarray(32,80),ciphertext:r.subarray(80,r.length)}}function VR(r){if(r.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:r.subarray(0,48),ciphertext:r.subarray(48,r.length)}}var zR=16;function $R(r,e){return async function*(t){for await(let n of t)for(let i=0;in.length&&(s=n.length);let o=r.encrypt(n.subarray(i,s),r.session);e?.encryptedPackets.increment(),yield pu(o.byteLength),yield o}}}function HR(r,e){return async function*(t){for await(let n of t)for(let i=0;in.length&&(s=n.length),s-zR(e==null&&(e=me((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(R1||(R1={}));var Bf;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identityKey!=null&&t.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(t.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||t.identitySig!=null&&t.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(t.identitySig??new Uint8Array(0))),t.extensions!=null&&(n.uint32(34),R1.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=R1.codec().decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(Bf||(Bf={}));async function GR(r,e,t){let n=await hH(r,WR(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return fH(r.publicKey,n,t)}function fH(r,e,t){return Bf.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function hH(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return(await _i(r.privateKey)).sign(e)}async function Vg(r){return Zr(r.identityKey)}function qg(r){return Bf.decode(r)}function WR(r){let e=G("noise-libp2p-static-key:");return ve([e,r],e.length+r.length)}async function zg(r,e,t){let n=await Zr(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=WR(r);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await vi(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Lf(r){return!(!(r instanceof Uint8Array)||r.length!==32)}function I1(r,e){for(let t=0;te[t])return 1}return r.byteLength>e.byteLength?1:r.byteLength{},{enabled:!1,trace:()=>{},error:()=>{}});function YR(r){Xn(`LOCAL_STATIC_PUBLIC_KEY ${U(r.publicKey,"hex")}`),Xn(`LOCAL_STATIC_PRIVATE_KEY ${U(r.privateKey,"hex")}`)}function $g(r){r?(Xn(`LOCAL_PUBLIC_EPHEMERAL_KEY ${U(r.publicKey,"hex")}`),Xn(`LOCAL_PRIVATE_EPHEMERAL_KEY ${U(r.privateKey,"hex")}`)):Xn("Missing local ephemeral keys.")}function QR(r){Xn(`REMOTE_STATIC_PUBLIC_KEY ${U(r,"hex")}`)}function Hg(r){Xn(`REMOTE_EPHEMERAL_PUBLIC_KEY ${U(r,"hex")}`)}function XR(r){r.cs1&&r.cs2?(Xn(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${U(r.cs1.k,"hex")}`),Xn(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${U(r.cs2.k,"hex")}`)):Xn("Missing cipher state.")}var dH="Cipherstate has reached maximum n, a new handshake must be performed",A1=class{n;bytes;view;constructor(e=0){this.n=e,this.bytes=new Uint8Array(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(dH)}};var T1=class{crypto;constructor(e){this.crypto=e}encryptWithAd(e,t,n){let i=this.encrypt(e.k,e.n,t,n);return e.n.increment(),i}decryptWithAd(e,t,n,i){let{plaintext:s,valid:o}=this.decrypt(e.k,e.n,t,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return fe(t,e)}encrypt(e,t,n,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),n,e)}encryptAndHash(e,t){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,n),n}decrypt(e,t,n,i,s){t.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,s);return o?{plaintext:o,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,t),{plaintext:n,valid:i}}dh(e,t){try{let n=this.crypto.generateX25519SharedKey(e,t);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return lr.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(ve([e,t],e.length+t.length))}mixKey(e,t){let[n,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new A1}}initializeSymmetric(e){let t=G(e,"utf-8"),n=this.hashProtocolName(t),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let t=new Uint8Array(32);return t.set(e),t}else return this.getHash(e,new Uint8Array(0))}split(e){let[t,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(t),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var D1=class extends T1{initializeInitiator(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}writeMessageA(e,t,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,t);return{ne:s,ns:i,ciphertext:o}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t);return{ne:n,ns:s,ciphertext:o}}writeMessageC(e,t){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,t){return Lf(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(Lf(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&Lf(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&Lf(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(t,n,s,i):o=this.initializeResponder(t,n,s,i),{hs:o,i:e,mc:0}}sendMessage(e,t,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,t,n);else if(e.mc===1)i=this.writeMessageB(e.hs,t);else if(e.mc===2){let{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,t){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,t));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,t));else if(e.mc===2){let{h:s,plaintext:o,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,t);n=o,i=a,e.h=s,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var C1=class{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;constructor(e,t,n,i,s,o,a,c){this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new D1(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(YR(this.session.hs.s),this.isInitiator){lr.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));await this.connection.write(LR(e)),lr.trace("Stage 0 - Initiator finished sending first message."),$g(this.session.hs.e)}else{lr.trace("Stage 0 - Responder waiting to receive first message...");let e=FR((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new sa("xx handshake stage 0 validation fail");lr.trace("Stage 0 - Responder received first message."),Hg(this.session.hs.re)}}async exchange(){if(this.isInitiator){lr.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=KR((await this.connection.read()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new sa("xx handshake stage 1 validation fail");lr.trace("Stage 1 - Initiator received the message."),Hg(this.session.hs.re),QR(this.session.hs.rs),lr.trace("Initiator going to check remote's signature...");try{let i=qg(t);this.remotePeer=this.remotePeer||await Vg(i),await zg(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new wl(`Error occurred while verifying signed payload: ${s.message}`)}lr.trace("All good with the signature!")}else{lr.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(MR(e)),lr.trace("Stage 1 - Responder sent the second handshake message with signed payload."),$g(this.session.hs.e)}}async finish(){if(this.isInitiator){lr.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(UR(e)),lr.trace("Stage 2 - Initiator sent message with signed payload.")}else{lr.trace("Stage 2 - Responder waiting for third handshake message...");let e=VR((await this.connection.read()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new sa("xx handshake stage 2 validation fail");lr.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=qg(t);this.remotePeer=this.remotePeer||await Vg(i),await zg(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new wl(`Error occurred while verifying signed payload: ${s.message}`)}}XR(this.session)}encrypt(e,t){let n=this.getCS(t);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,t,n){let i=this.getCS(t,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new sa("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function jR(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var P1=class{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;constructor(e={}){let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??Kg,this.extensions=n,this.metrics=o?jR(o):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,t,n){let i=Cf(t,{lengthEncoder:pu,lengthDecoder:Nf,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,n){let i=Cf(t,{lengthEncoder:pu,lengthDecoder:Nf,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let t=await GR(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new C1(n,t,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return o}async createSecureConnection(e,t){let[n,i]=vR(),s=e.unwrap();return await Me(n,$R(t,this.metrics),s,o=>Yt(o,{lengthDecoder:Nf}),HR(t,this.metrics),n),i}};function mu(r={}){return()=>new P1(r)}var gu="ERR_INVALID_FRAME",Gg="ERR_UNREQUESTED_PING",Wg="ERR_NOT_MATCHING_PING",Yg="ERR_STREAM_ALREADY_EXISTS",Qg="ERR_DECODE_INVALID_VERSION",Xg="ERR_BOTH_CLIENTS",jg="ERR_RECV_WINDOW_EXCEEDED",ZR=new Set([gu,Gg,Wg,Yg,Qg,Xg,jg]),So="ERR_INVALID_CONFIG",k1="ERR_MUXER_LOCAL_CLOSED",Zg="ERR_MUXER_REMOTE_CLOSED";var JR="ERR_STREAM_ABORT",eI="ERROR_MAX_OUTBOUND_STREAMS_EXCEEDED",tI="ERR_DECODE_IN_PROGRESS",Mf=256*1024,rI=16*1024*1024;var nI={log:C("libp2p:yamux"),enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:Mf,maxStreamWindowSize:rI,maxMessageSize:64*1024};function iI(r){if(r.keepAliveInterval<=0)throw new w("keep-alive interval must be positive",So);if(r.maxInboundStreams<0)throw new w("max inbound streams must be larger or equal 0",So);if(r.maxOutboundStreams<0)throw new w("max outbound streams must be larger or equal 0",So);if(r.initialStreamWindowSize2**32-1)throw new w("MaxStreamWindowSize must be less than equal MAX_UINT32",So);if(r.maxMessageSize<1024)throw new w("MaxMessageSize must be greater than a kilobyte",So)}var Tt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Tt||(Tt={}));var wt;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(wt||(wt={}));var pH=Object.values(wt).filter(r=>typeof r!="string"),sI=0,jn;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(jn||(jn={}));var Ro=12;function Jg(r){let e=pH.filter(t=>(r.flag&t)===t).map(t=>wt[t]).join("|");return`streamID=${r.streamID} type=${Tt[r.type]} flag=${e} length=${r.length}`}var oI=2**24;function mH(r){if(r[0]!==sI)throw new w("Invalid frame version",Qg);return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*oI+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*oI+(r[9]<<16)+(r[10]<<8)+r[11]}}var N1=class{source;buffer;frameInProgress;constructor(e){this.source=gH(e),this.buffer=new Te,this.frameInProgress=!1}async*emitFrames(){for await(let e of this.source)for(this.buffer.append(e);;){let t=this.readHeader();if(t===void 0)break;let{type:n,length:i}=t;n===Tt.Data?(this.frameInProgress=!0,yield{header:t,readData:this.readBytes.bind(this,i)}):yield{header:t}}}readHeader(){if(this.frameInProgress)throw new w("decoding frame already in progress",tI);if(this.buffer.length=e)break}let t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}};function gH(r){if(r[Symbol.iterator]!==void 0){let e=r[Symbol.iterator]();return e.return=void 0,{[Symbol.iterator](){return e}}}else if(r[Symbol.asyncIterator]!==void 0){let e=r[Symbol.asyncIterator]();return e.return=void 0,{[Symbol.asyncIterator](){return e}}}else throw new Error("a source must be either an iterable or an async iterable")}function ey(r){let e=new Uint8Array(Ro);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var yH="ERR_STREAM_RESET",bH="ERR_SINK_INVALID_STATE";function ty(r){return r!=null&&typeof r.then=="function"}var Io=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;sinkController;sinkEnd;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;log;constructor(e){this.sinkController=new AbortController,this.sinkEnd=Le(),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.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=Pt({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.readStatus="closed",this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new w(`writable end state is "${this.writeStatus}" not "ready"`,bH);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let n=this.sendNewStream(t);ty(n)&&await n}e=Er(e,this.sinkController.signal,{returnOnAbort:!0}),this.log.trace("sink reading from source");for await(let n of e){n=n instanceof Uint8Array?new Te(n):n;let i=this.sendData(n,t);ty(i)&&await i}this.log.trace("sink finished reading from source"),this.writeStatus="done",this.log.trace("sink calling closeWrite"),await this.closeWrite(t),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(e),this.closeWrite(e)]),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",t==="ready"&&(this.log.trace("ending internal source queue"),this.streamSource.end()),this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),this.log.trace("closed readable end of stream")}async closeWrite(e={}){if(this.writeStatus==="closing"||this.writeStatus==="closed")return;this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus);let t=this.writeStatus;this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await this.sink([])),this.writeStatus="closing",t==="writing"&&await new Promise((n,i)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),this.sinkEnd.promise.then(n,i)})}),this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeWrite==null&&(this.log.trace("send close write to remote"),await this.sendCloseWrite(e)),this.writeStatus="closed",this.log.trace("closed writable end of stream")}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();ty(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new w("stream reset",yH);this.status="reset",this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("muxer destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var Zn;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished"})(Zn||(Zn={}));var O1=class extends Io{name;state;config;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;sendFrame;constructor(e){super({...e,onEnd:t=>{this.state=Zn.Finished,e.onEnd?.(t)}}),this.config=e.config,this._id=parseInt(e.id,10),this.name=e.name,this.state=e.state,this.sendWindowCapacity=Mf,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.source=ia(this.source,()=>{this.sendWindowUpdate()})}async sendNewStream(){}async sendData(e,t={}){for(e=e.sublist();e.byteLength!==0;){if(this.sendWindowCapacity===0&&await this.waitForSendWindowCapacity(t),this.status!=="open")return;let n=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-Ro,e.length),i=this.getSendFlags();this.sendFrame({type:Tt.Data,flag:i,streamID:this._id,length:n},e.subarray(0,n)),this.sendWindowCapacity-=n,e.consume(n)}}async sendReset(){this.sendFrame({type:Tt.WindowUpdate,flag:wt.RST,streamID:this._id,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|wt.FIN;this.sendFrame({type:Tt.WindowUpdate,flag:e,streamID:this._id,length:0})}async sendCloseRead(){}async waitForSendWindowCapacity(e={}){if(this.sendWindowCapacity>0)return;let t,n,i=()=>{this.status==="open"?n(new w("stream aborted",JR)):t()};e.signal?.addEventListener("abort",i);try{await new Promise((s,o)=>{this.sendWindowCapacityUpdate=()=>{s()},n=o,t=s})}finally{e.signal?.removeEventListener("abort",i)}}handleWindowUpdate(e){this.log?.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,t===0&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace("stream received data id=%s",this._id),this.processFlags(e.flag),this.recvWindowCapacity0&&t-this.epochStart=this.recvWindow&&e===0)return;let i=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Tt.WindowUpdate,flag:e,streamID:this._id,length:i})}};var aI="/yamux/1.0.0",wH=500,B1=class{protocol=aI;_init;constructor(e={}){this._init=e}createStreamMuxer(e){return new ry({...this._init,...e})}},ry=class{protocol=aI;source;sink;config;log;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e){this.client=e.direction==="outbound",this.config={...nI,...e},this.log=this.config.log,iI(this.config),this.closeController=new AbortController,this.onIncomingStream=e.onIncomingStream,this.onStreamEnd=e.onStreamEnd,this._streams=new Map,this.source=Pt({onEnd:()=>{this.log?.trace("muxer source ended"),this._streams.forEach(t=>{t.destroy()})}}),this.sink=async t=>{t=Er(t,this.closeController.signal,{returnOnAbort:!0});let n,i;try{let s=new N1(t);await Me(s.emitFrames.bind(s),async o=>{for await(let{header:a,readData:c}of o)await this.handleFrame(a,c)}),n=jn.NormalTermination}catch(s){let o=s.code;ZR.has(o)?(this.log?.error("protocol error in sink",s),n=jn.ProtocolError):(this.log?.error("internal error in sink",s),n=jn.InternalError),i=s}this.log?.trace("muxer sink ended"),i!=null?this.abort(i,n):await this.close({reason:n})},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=0,this.log?.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch(t=>this.log?.error("keepalive error: %s",t))}get streams(){return Array.from(this._streams.values())}newStream(e){if(this.remoteGoAway!==void 0)throw new w("muxer closed remotely",Zg);if(this.localGoAway!==void 0)throw new w("muxer closed locally",k1);let t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new w("max outbound streams exceeded",eI);this.log?.trace("new outgoing stream id=%s",t);let n=this._newStream(t,e,Zn.Init,"outbound");return this._streams.set(t,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}async ping(){if(this.remoteGoAway!==void 0)throw new w("muxer closed remotely",Zg);if(this.localGoAway!==void 0)throw new w("muxer closed locally",k1);if(this.activePing===void 0){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise((i,s)=>{let o=()=>{s(new w("muxer closed locally",k1))};this.closeController.signal.addEventListener("abort",o,{once:!0}),e=()=>{this.closeController.signal.removeEventListener("abort",o),i()}}),resolve:e};let t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}let n=Date.now();this.rtt=n-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.closeController.signal.aborted)return;let t=e?.reason??jn.NormalTermination;this.log?.trace("muxer close reason=%s",t),e.signal=e.signal??AbortSignal.timeout(wH);try{await Promise.all([...this._streams.values()].map(async n=>n.close(e))),this.sendGoAway(t),this._closeMuxer()}catch(n){this.abort(n)}}abort(e,t){if(!this.closeController.signal.aborted){t=t??jn.InternalError,this.log?.error("muxer abort reason=%s error=%s",t,e);for(let n of this._streams.values())n.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,n,i){if(this._streams.get(e)!=null)throw new w("Stream already exists",Yg,{id:e});let s=new O1({id:e.toString(),name:t,state:n,direction:i,sendFrame:this.sendFrame.bind(this),onEnd:()=>{this.closeStream(e),this.onStreamEnd?.(s)},log:C(`libp2p:yamux:${i}:${e}`),config:this.config,getRTT:this.getRTT.bind(this)});return s}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){let e=new Promise((t,n)=>{this.closeController.signal.addEventListener("abort",n,{once:!0})});for(this.log?.trace("muxer keepalive enabled interval=%s",this.config.keepAliveInterval);;){let t;try{await Promise.race([e,new Promise(n=>{t=setTimeout(n,this.config.keepAliveInterval)})]),this.ping().catch(n=>this.log?.error("ping error: %s",n))}catch{clearInterval(t);return}}}async handleFrame(e,t){let{streamID:n,type:i,length:s}=e;if(this.log?.trace("received frame %s",Jg(e)),n===0)switch(i){case Tt.Ping:{this.handlePing(e);return}case Tt.GoAway:{this.handleGoAway(s);return}default:throw new w("Invalid frame type",gu,{header:e})}else switch(e.type){case Tt.Data:case Tt.WindowUpdate:{await this.handleStreamMessage(e,t);return}default:throw new w("Invalid frame type",gu,{header:e})}}handlePing(e){if(e.flag===wt.SYN)this.log?.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,wt.ACK);else if(e.flag===wt.ACK)this.log?.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new w("Invalid frame flag",gu,{header:e})}handlePingResponse(e){if(this.activePing===void 0)throw new w("ping not requested",Gg);if(this.activePing.id!==e)throw new w("ping doesn't match our id",Wg);this.activePing.resolve()}handleGoAway(e){this.log?.trace("received GoAway reason=%s",jn[e]??"unknown"),this.remoteGoAway=e;for(let t of this._streams.values())t.reset();this._closeMuxer()}async handleStreamMessage(e,t){let{streamID:n,flag:i,type:s}=e;(i&wt.SYN)===wt.SYN&&this.incomingStream(n);let o=this._streams.get(n);if(o===void 0){if(s===Tt.Data){if(this.log?.("discarding data for stream id=%s",n),t===void 0)throw new Error("unreachable");await t()}else this.log?.("frame for missing stream id=%s",n);return}switch(s){case Tt.WindowUpdate:{o.handleWindowUpdate(e);return}case Tt.Data:{if(t===void 0)throw new Error("unreachable");await o.handleData(e,t);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new w("both endpoints are clients",Xg);if(this._streams.has(e))return;if(this.log?.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Tt.WindowUpdate,flag:wt.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.config.maxInboundStreams){this.log?.("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Tt.WindowUpdate,flag:wt.RST,streamID:e,length:0});return}let t=this._newStream(e,void 0,Zn.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace("sending frame %s",Jg(e)),e.type===Tt.Data){if(t===void 0)throw new w("invalid frame",gu);this.source.push(ey(e)),this.source.push(t)}else this.source.push(ey(e))}sendPing(e,t=wt.SYN){t===wt.SYN?this.log?.trace("sending ping request pingId=%s",e):this.log?.trace("sending ping response pingId=%s",e),this.sendFrame({type:Tt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=jn.NormalTermination){this.log?.("sending GoAway reason=%s",jn[e]),this.localGoAway=e,this.sendFrame({type:Tt.GoAway,flag:0,streamID:0,length:e})}};function cI(r={}){return()=>new B1(r)}var EH=ne("dns4"),xH=ne("dns6"),vH=ne("dnsaddr"),To=zt(ne("dns"),vH,EH,xH),L1=zt(ne("ip4"),ne("ip6")),yu=zt(Ee(L1,ne("tcp")),Ee(To,ne("tcp"))),M1=Ee(L1,ne("udp")),_H=Ee(M1,ne("utp")),SH=Ee(M1,ne("quic")),RH=Ee(M1,ne("quic-v1")),ny=zt(Ee(yu,ne("ws")),Ee(To,ne("ws"))),bu=zt(Ee(ny,ne("p2p")),ny),iy=zt(Ee(yu,ne("wss")),Ee(To,ne("wss")),Ee(yu,ne("tls"),ne("ws")),Ee(To,ne("tls"),ne("ws"))),qa=zt(Ee(iy,ne("p2p")),iy),sy=zt(Ee(yu,ne("http")),Ee(L1,ne("http")),Ee(To,ne("http"))),oy=zt(Ee(yu,ne("https")),Ee(L1,ne("https")),Ee(To,ne("https"))),uI=Ee(M1,ne("webrtc-direct"),ne("certhash")),hI=zt(Ee(uI,ne("p2p")),uI),lI=Ee(RH,ne("webtransport"),ne("certhash"),ne("certhash")),dI=zt(Ee(lI,ne("p2p")),lI),pI=zt(Ee(bu,ne("p2p-webrtc-star"),ne("p2p")),Ee(qa,ne("p2p-webrtc-star"),ne("p2p")),Ee(bu,ne("p2p-webrtc-star")),Ee(qa,ne("p2p-webrtc-star"))),h8e=zt(Ee(bu,ne("p2p-websocket-star"),ne("p2p")),Ee(qa,ne("p2p-websocket-star"),ne("p2p")),Ee(bu,ne("p2p-websocket-star")),Ee(qa,ne("p2p-websocket-star"))),mI=zt(Ee(sy,ne("p2p-webrtc-direct"),ne("p2p")),Ee(oy,ne("p2p-webrtc-direct"),ne("p2p")),Ee(sy,ne("p2p-webrtc-direct")),Ee(oy,ne("p2p-webrtc-direct"))),za=zt(ny,iy,sy,oy,pI,mI,yu,_H,SH,To,hI,dI),d8e=zt(Ee(za,ne("p2p-stardust"),ne("p2p")),Ee(za,ne("p2p-stardust"))),Ao=zt(Ee(za,ne("p2p")),pI,mI,hI,dI,ne("p2p")),fI=zt(Ee(Ao,ne("p2p-circuit"),Ao),Ee(Ao,ne("p2p-circuit")),Ee(ne("p2p-circuit"),Ao),Ee(za,ne("p2p-circuit")),Ee(ne("p2p-circuit"),za),ne("p2p-circuit")),gI=()=>zt(Ee(fI,gI),fI),Ai=gI(),yI=zt(Ee(Ai,Ao,Ai),Ee(Ao,Ai),Ee(Ai,Ao),Ai,Ao);var p8e=zt(Ee(Ai,ne("webrtc"),ne("p2p")),Ee(Ai,ne("webrtc")),Ee(za,ne("webrtc"),ne("p2p")),Ee(za,ne("webrtc")),ne("webrtc"));function bI(r){function e(t){let n;try{n=ge(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function Ee(...r){function e(t){if(t.length(n=typeof i=="function"?i().partialMatch(t):i.partialMatch(t),Array.isArray(n)&&(t=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:bI(e),partialMatch:e}}function zt(...r){function e(n){let i=null;return r.some(s=>{let o=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return o!=null?(i=o,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:bI(e),partialMatch:e}}function ne(r){let e=r;function t(i){let s;try{s=ge(i)}catch{return!1}let o=s.protoNames();return o.length===1&&o[0]===e}function n(i){return i.length===0?null:i[0]===e?i.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:n}}var U1=C("libp2p:bootstrap"),IH="bootstrap",AH=50,TH=12e4,DH=1e3,ay=class extends Ye{static tag="bootstrap";timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.timeout=t.timeout??DH,this.list=[];for(let n of t.list){if(!yI.matches(n)){U1.error("Invalid multiaddr");continue}let i=ge(n),s=i.getPeerId();if(s==null){U1.error("Invalid bootstrap multiaddr without peer id");continue}let o={id:we(s),multiaddrs:[i],protocols:[]};this.list.push(o)}this._init=t}[Ta]=this;[Symbol.toStringTag]="@libp2p/bootstrap";isStarted(){return!!this.timer}start(){this.isStarted()||(U1("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{U1.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??IH]:{value:this._init.tagValue??AH,ttl:this._init.tagTTL??TH}}}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function EI(r){return e=>new ay(e,r)}async function*cy(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var II=j(SI(),1);var K1=C("ipni-content-routing"),RI={concurrentRequests:4,timeout:3e4},ly=class{started;httpQueue;shutDownController;clientUrl;timeout;constructor(e,t={}){K1("enabled IPNI routing via",e),this.started=!1,this.shutDownController=new AbortController,this.httpQueue=new kt({concurrency:t.concurrentRequests??RI.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??RI.timeout}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*findProviders(e,t={}){K1("findProviders starts: %c",e);let n=er([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),i=Le(),s=Le();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let o=`${this.clientUrl}cid/${e.toString()}?cascade=ipfs-dht`,c=await fetch(o,{headers:{Accept:"application/x-ndjson"},signal:n});if(c.body==null)throw new w("IPNI response had no body","ERR_BAD_RESPONSE");for await(let u of(0,II.default)(cy(c.body)))u.Metadata==="gBI="&&(yield this.mapEvent(u))}catch(o){K1.error("findProviders errored:",o)}finally{n.clear(),s.resolve(),K1("findProviders finished: %c",e)}}mapEvent(e){let t=we(e.Provider.ID),n=[];for(let s of e.Provider.Addrs){let o=ge(s);n.push(o)}return{id:t,multiaddrs:n,protocols:[]}}async provide(){}async put(){}async get(){throw new w("Not found","ERR_NOT_FOUND")}};function AI(r,e={}){return()=>new ly(r,e)}var TI="/lan",DI="/ipfs",CI="/kad/1.0.0",PI="/dht/record",fy="/dht/provider";var V1=globalThis.CustomEvent??Event;async function*$a(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,s=[],o=Le(),a=Le(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(o=Le(),await o.promise),l)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,i.dispatchEvent(new V1("task-complete"))},g=>{m.done=!0,m.err=g,i.dispatchEvent(new V1("task-complete"))})}c=!0,i.dispatchEvent(new V1("task-complete"))}catch(p){u=p,i.dispatchEvent(new V1("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*h(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,o.resolve(),p.err;o.resolve()}}function*d(){for(;f();)for(let p=0;p(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.key!=null&&t.key.byteLength>0&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&t.value.byteLength>0&&(n.uint32(18),n.bytes(t.value)),t.timeReceived!=null&&t.timeReceived!==""&&(n.uint32(42),n.string(t.timeReceived)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={key:new Uint8Array(0),value:new Uint8Array(0),timeReceived:""},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.bytes();break;case 2:i.value=t.bytes();break;case 5:i.timeReceived=t.string();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(Uf||(Uf={}));function kI(r){let e=r.getUTCFullYear(),t=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),i=String(r.getUTCHours()).padStart(2,"0"),s=String(r.getUTCMinutes()).padStart(2,"0"),o=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${i}:${s}:${o}.${c}Z`}function NI(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,s=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),u=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,s,o,a,c,u))}var vr=class r{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return Uf.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:kI(this.timeReceived)}}static deserialize(e){let t=Uf.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=NI(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new r(e.key,e.value,t)}};var OI;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.key!=null&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&(n.uint32(18),n.bytes(t.value)),t.author!=null&&(n.uint32(26),n.bytes(t.author)),t.signature!=null&&(n.uint32(34),n.bytes(t.signature)),t.timeReceived!=null&&(n.uint32(42),n.string(t.timeReceived)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.key=t.bytes();break;case 2:i.value=t.bytes();break;case 3:i.author=t.bytes();break;case 4:i.signature=t.bytes();break;case 5:i.timeReceived=t.string();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(OI||(OI={}));var Do;(function(r){let e;(function(a){a.PUT_VALUE="PUT_VALUE",a.GET_VALUE="GET_VALUE",a.ADD_PROVIDER="ADD_PROVIDER",a.GET_PROVIDERS="GET_PROVIDERS",a.FIND_NODE="FIND_NODE",a.PING="PING"})(e=r.MessageType||(r.MessageType={}));let t;(function(a){a[a.PUT_VALUE=0]="PUT_VALUE",a[a.GET_VALUE=1]="GET_VALUE",a[a.ADD_PROVIDER=2]="ADD_PROVIDER",a[a.GET_PROVIDERS=3]="GET_PROVIDERS",a[a.FIND_NODE=4]="FIND_NODE",a[a.PING=5]="PING"})(t||(t={})),function(a){a.codec=()=>ft(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(a){a.NOT_CONNECTED="NOT_CONNECTED",a.CONNECTED="CONNECTED",a.CAN_CONNECT="CAN_CONNECT",a.CANNOT_CONNECT="CANNOT_CONNECT"})(n=r.ConnectionType||(r.ConnectionType={}));let i;(function(a){a[a.NOT_CONNECTED=0]="NOT_CONNECTED",a[a.CONNECTED=1]="CONNECTED",a[a.CAN_CONNECT=2]="CAN_CONNECT",a[a.CANNOT_CONNECT=3]="CANNOT_CONNECT"})(i||(i={})),function(a){a.codec=()=>ft(i)}(n=r.ConnectionType||(r.ConnectionType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=me((u,l,f={})=>{if(f.lengthDelimited!==!1&&l.fork(),u.id!=null&&(l.uint32(10),l.bytes(u.id)),u.addrs!=null)for(let h of u.addrs)l.uint32(18),l.bytes(h);u.connection!=null&&(l.uint32(24),r.ConnectionType.codec().encode(u.connection,l)),f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={addrs:[]},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.id=u.bytes();break;case 2:f.addrs.push(u.bytes());break;case 3:f.connection=r.ConnectionType.codec().decode(u);break;default:u.skipType(d&7);break}}return f})),c),a.encode=u=>pe(u,a.codec()),a.decode=u=>de(u,a.codec())})(s=r.Peer||(r.Peer={}));let o;r.codec=()=>(o==null&&(o=me((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.MessageType.codec().encode(a.type,c)),a.clusterLevelRaw!=null&&(c.uint32(80),c.int32(a.clusterLevelRaw)),a.key!=null&&(c.uint32(18),c.bytes(a.key)),a.record!=null&&(c.uint32(26),c.bytes(a.record)),a.closerPeers!=null)for(let l of a.closerPeers)c.uint32(66),r.Peer.codec().encode(l,c);if(a.providerPeers!=null)for(let l of a.providerPeers)c.uint32(74),r.Peer.codec().encode(l,c);u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={closerPeers:[],providerPeers:[]},l=c==null?a.len:a.pos+c;for(;a.pos>>3){case 1:u.type=r.MessageType.codec().decode(a);break;case 10:u.clusterLevelRaw=a.int32();break;case 2:u.key=a.bytes();break;case 3:u.record=a.bytes();break;case 8:u.closerPeers.push(r.Peer.codec().decode(a,a.uint32()));break;case 9:u.providerPeers.push(r.Peer.codec().decode(a,a.uint32()));break;default:a.skipType(f&7);break}}return u})),o),r.encode=a=>pe(a,r.codec()),r.decode=a=>de(a,r.codec())})(Do||(Do={}));var $t=Do.MessageType,PH=Do.ConnectionType,MI=Object.keys($t),Bt=class r{type;key;clusterLevelRaw;closerPeers;providerPeers;record;constructor(e,t,n){if(!(t instanceof Uint8Array))throw new Error("Key must be a Uint8Array");this.type=e,this.key=t,this.clusterLevelRaw=n,this.closerPeers=[],this.providerPeers=[],this.record=void 0}get clusterLevel(){let e=this.clusterLevelRaw-1;return e<0?0:e}set clusterLevel(e){this.clusterLevelRaw=e}serialize(){return Do.encode({key:this.key,type:this.type,clusterLevelRaw:this.clusterLevelRaw,closerPeers:this.closerPeers.map(BI),providerPeers:this.providerPeers.map(BI),record:this.record==null?void 0:this.record.serialize().subarray()})}static deserialize(e){let t=Do.decode(e),n=new r(t.type??Do.MessageType.PUT_VALUE,t.key??Uint8Array.from([]),t.clusterLevelRaw??0);return n.closerPeers=t.closerPeers.map(LI),n.providerPeers=t.providerPeers.map(LI),t.record?.length!=null&&(n.record=vr.deserialize(t.record)),n}};function BI(r){return{id:r.id.toBytes(),addrs:(r.multiaddrs??[]).map(t=>t.bytes),connection:PH.CONNECTED}}function LI(r){if(r.id==null)throw new Error("Invalid peer in message");return{id:Ot(r.id),multiaddrs:(r.addrs??[]).map(e=>ge(e)),protocols:[]}}function hy(r,e={}){let t={...r,name:"SEND_QUERY",type:0,messageName:r.type,messageType:MI.indexOf(r.type.toString())};return e.onProgress?.(new nt("kad-dht:query:send-query",{detail:t})),t}function Ff(r,e={}){let t={...r,name:"PEER_RESPONSE",type:1,messageName:r.messageType,closer:r.closer!=null?r.closer:[],providers:r.providers!=null?r.providers:[]};return e.onProgress?.(new nt("kad-dht:query:peer-response",{detail:t})),t}function q1(r,e={}){let t={...r,name:"FINAL_PEER",type:2};return e.onProgress?.(new nt("kad-dht:query:final-peer",{detail:t})),t}function $r(r,e={}){let t={...r,name:"QUERY_ERROR",type:3};return e.onProgress?.(new nt("kad-dht:query:query-error",{detail:t})),t}function dy(r,e={}){let t={...r,name:"PROVIDER",type:4};return e.onProgress?.(new nt("kad-dht:query:provider",{detail:t})),t}function Kf(r,e={}){let t={...r,name:"VALUE",type:5};return e.onProgress?.(new nt("kad-dht:query:value",{detail:t})),t}function py(r,e={}){let t={...r,name:"DIAL_PEER",type:7};return e.onProgress?.(new nt("kad-dht:query:dial-peer",{detail:t})),t}function UI(r,e,t){if(t.length===0){let o="No records given";throw new w(o,"ERR_NO_RECORDS_RECEIVED")}let i=U(e).split("/");if(i.length<3){let o="Record key does not have a selector function";throw new w(o,"ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")}let s=r[i[1].toString()];if(s==null){let o=`Unrecognized key prefix: ${i[1]}`;throw new w(o,"ERR_UNRECOGNIZED_KEY_PREFIX")}return t.length===1?0:s(e,t)}function kH(r,e){return 0}var FI={pk:kH};async function wu(r,e){let t=e.key,i=U(t).split("/");if(i.length<3)return;let s=r[i[1].toString()];if(s==null){let o="Invalid record keytype";throw new w(o,"ERR_INVALID_RECORD_KEY_TYPE")}await s(t,e.value)}var NH=async(r,e)=>{if(!(r instanceof Uint8Array))throw new w('"key" must be a Uint8Array',"ERR_INVALID_RECORD_KEY_NOT_BUFFER");if(r.byteLength<5)throw new w("invalid public key record","ERR_INVALID_RECORD_KEY_TOO_SHORT");if(U(r.subarray(0,4))!=="/pk/")throw new w("key was not prefixed with /pk/","ERR_INVALID_RECORD_KEY_BAD_PREFIX");let n=r.slice(4),i=await Ke.digest(e);if(!fe(n,i.bytes))throw new w("public key does not match passed in key","ERR_INVALID_RECORD_HASH_MISMATCH")},KI={pk:NH};var OH=G("/pk/");function Eu(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>{let[[t,n]]=e.stringTuples();if(t===53||t===54||t===55)return n!=="localhost";if(t!==4&&t!==6||n==null)return!1;let i=Jr(n);return i==null?!0:!i})}}function xu(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>{let[[t,n]]=e.stringTuples();if(n==="localhost")return!0;if(t!==4&&t!==6||n==null)return!1;let i=Jr(n);return i??!1})}}async function Co(r){return(await Ke.digest(r)).digest}async function Ti(r){return Co(r.toBytes())}function Ms(r){return new pt(`${PI}/${U(r,"base32")}`,!1)}function VI(r){return ve([OH,r.toBytes()])}function qI(r){return U(r.subarray(0,4))==="/pk/"}function zI(r){return Ot(r.subarray(4))}function my(r,e){let t=new Date;return new vr(r,e,t).serialize()}function $I(r,e=100){let t;return()=>{clearTimeout(t),t=setTimeout(()=>{r()},e)}}var z1=class{log;components;validators;selectors;peerRouting;queryManager;network;constructor(e,t){let{validators:n,selectors:i,peerRouting:s,queryManager:o,network:a,lan:c}=t;this.components=e,this.log=C(`libp2p:kad-dht:${c?"lan":"wan"}:content-fetching`),this.validators=n,this.selectors=i,this.peerRouting=s,this.queryManager=o,this.network=a}async putLocal(e,t){let n=Ms(e);await this.components.datastore.put(n,t)}async getLocal(e){this.log("getLocal %b",e);let t=Ms(e);this.log("fetching record for key %k",t);let n=await this.components.datastore.get(t);this.log("found %k in local datastore",t);let i=vr.deserialize(n);return await wu(this.validators,i),i}async*sendCorrectionRecord(e,t,n,i={}){this.log("sendCorrection for %b",e);let s=my(e,n);for(let{value:o,from:a}of t){if(fe(o,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{let l=Ms(e);this.log(`Storing corrected record for key ${l.toString()}`),await this.components.datastore.put(l,s.subarray())}catch(l){this.log.error("Failed error correcting self",l)}continue}let c=!1,u=new Bt($t.PUT_VALUE,e,0);u.record=vr.deserialize(s);for await(let l of this.network.sendRequest(a,u,i))l.name==="PEER_RESPONSE"&&l.record!=null&&fe(l.record.value,vr.deserialize(s).value)&&(c=!0),yield l;c||(yield $r({from:a,error:new w("value not put correctly","ERR_PUT_VALUE_INVALID")},i)),this.log.error("Failed error correcting entry")}}async*put(e,t,n={}){this.log("put key %b value %b",e,t);let i=my(e,t),s=Ms(e);this.log(`storing record for key ${s.toString()}`),await this.components.datastore.put(s,i.subarray()),yield*Me(this.peerRouting.getClosestPeers(e,{signal:n.signal}),o=>oi(o,a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[],u=new Bt($t.PUT_VALUE,e,0);u.record=vr.deserialize(i),this.log("send put to %p",a.peer.id);for await(let l of this.network.sendRequest(a.peer.id,u,n))c.push(l),l.name==="PEER_RESPONSE"&&(l.record!=null&&fe(l.record.value,vr.deserialize(i).value)||c.push($r({from:a.peer.id,error:new w("value not put correctly","ERR_PUT_VALUE_INVALID")},n)));return c}),o=>$a(o,{ordered:!1,concurrency:3}),async function*(o){for await(let a of o)yield*a})}async*get(e,t={}){this.log("get %b",e);let n=[];for await(let a of this.getMany(e,t))a.name==="VALUE"&&n.push(a),yield a;if(n.length===0)return;let i=n.map(a=>a.value),s=0;try{s=UI(this.selectors,e,i)}catch(a){if(a.code!=="ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")throw a}let o=i[s];if(this.log("GetValue %b %b",e,o),o==null)throw new w("best value was not found","ERR_NOT_FOUND");yield*this.sendCorrectionRecord(e,n,o,t),yield n[s]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{let s=await this.getLocal(e);yield Kf({value:s.value,from:this.components.peerId},t)}catch(s){this.log("error getting local value for %b",e,s)}let n=this,i=async function*({peer:s,signal:o}){for await(let a of n.peerRouting.getValueOrPeers(s,e,{signal:o}))yield a,a.name==="PEER_RESPONSE"&&a.record!=null&&(yield Kf({from:s,value:a.record.value},t))};yield*this.queryManager.run(e,i,t)}};var $1=class{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){let{network:n,peerRouting:i,queryManager:s,routingTable:o,providers:a,lan:c}=t;this.components=e,this.log=C(`libp2p:kad-dht:${c?"lan":"wan"}:content-routing`),this.network=n,this.peerRouting=i,this.queryManager=s,this.routingTable=o,this.providers=a}async*provide(e,t,n={}){this.log("provide %s",e),await this.providers.addProvider(e,this.components.peerId);let i=new Bt($t.ADD_PROVIDER,e.multihash.bytes,0);i.providerPeers=[{id:this.components.peerId,multiaddrs:t,protocols:[]}];let s=0,o=a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[];this.log("putProvider %s to %p",e,a.peer.id);try{this.log("sending provider record for %s to %p",e,a.peer.id);for await(let u of this.network.sendMessage(a.peer.id,i,n))u.name==="PEER_RESPONSE"&&(this.log("sent provider record for %s to %p",e,a.peer.id),s++),c.push(u)}catch(u){this.log.error("error sending provide record to peer %p",a.peer.id,u),c.push($r({from:a.peer.id,error:u},n))}return c};yield*Me(this.peerRouting.getClosestPeers(e.multihash.bytes,n),a=>oi(a,c=>o(c)),a=>$a(a,{ordered:!1,concurrency:3}),async function*(a){for await(let c of a)yield*c}),this.log("sent provider records to %d peers",s)}async*findProviders(e,t){let n=this.routingTable.kBucketSize,i=e.multihash.bytes,s=this;this.log("findProviders %c",e);let o=await this.providers.getProviders(e);if(o.length>0){let u=[];for(let l of o.slice(0,n))try{let f=await this.components.peerStore.get(l);u.push({id:l,multiaddrs:f.addresses.map(({multiaddr:h})=>h),protocols:f.protocols})}catch(f){if(f.code!=="ERR_NOT_FOUND")throw f;this.log("no peer store entry for %p",l)}yield Ff({from:this.components.peerId,messageType:$t.GET_PROVIDERS,providers:u},t),yield dy({from:this.components.peerId,providers:u},t)}if(o.length>=n)return;let a=async function*({peer:u,signal:l}){let f=new Bt($t.GET_PROVIDERS,i,0);yield*s.network.sendRequest(u,f,{...t,signal:l})},c=new Set(o.map(u=>u.toString()));for await(let u of this.queryManager.run(i,a,t))if(yield u,u.name==="PEER_RESPONSE"){this.log("Found %d provider entries for %c and %d closer peers",u.providers.length,e,u.closer.length);let l=[];for(let f of u.providers)c.has(f.id.toString())||(c.add(f.id.toString()),l.push(f));if(l.length>0&&(yield dy({from:u.from,providers:l},t)),c.size===n)return}}};var H1=class extends Ye{log;protocol;running;components;constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=C(`libp2p:kad-dht:${i?"lan":"wan"}:network`),this.running=!1,this.protocol=n}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield py({peer:e},n),yield hy({to:e,type:t.type},n);let i;try{let o=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n),a=await this._writeReadMessage(o,t.serialize(),n);yield Ff({from:e,messageType:a.type,closer:a.closerPeers,providers:a.providerPeers,record:a.record},n)}catch(s){yield $r({from:e,error:s},n)}finally{i!=null&&await i.close()}}async*sendMessage(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield py({peer:e},n),yield hy({to:e,type:t.type},n);let i;try{let o=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n);await this._writeMessage(o,t.serialize(),n),yield Ff({from:e,messageType:t.type},n)}catch(s){yield $r({from:e,error:s},n)}finally{i!=null&&await i.close()}}async _writeMessage(e,t,n){n.signal!=null&&(e=Ri(e,n.signal)),await Me([t],i=>Kt(i),e,Wr)}async _writeReadMessage(e,t,n){n.signal!=null&&(e=Ri(e,n.signal));let i=await Me([t],o=>Kt(o),e,o=>Yt(o),async o=>{let a=await Ns(o);if(a!=null)return a;throw new w("No message received","ERR_NO_MESSAGE_RECEIVED")}),s=Bt.deserialize(i);return s.closerPeers.forEach(o=>{this.dispatchEvent(new nt("peer",{detail:o}))}),s.providerPeers.forEach(o=>{this.dispatchEvent(new nt("peer",{detail:o}))}),s}};var G1=class{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return this.peerDistances.map(e=>e.peerId)}async add(e){if(this.peerDistances.find(i=>i.peerId.equals(e))!=null)return;let t=await Ti(e),n={peerId:e,distance:Ls(this.originDhtKey,t)};this.peerDistances.push(n),this.peerDistances.sort((i,s)=>I1(i.distance,s.distance)),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async anyCloser(e){if(e.length===0)return!1;if(this.length===0)return!0;let t=await Promise.all(e.map(Ti)),n=this.peerDistances[this.peerDistances.length-1].distance;for(let i of t){let s=Ls(this.originDhtKey,i);if(I1(s,n)<0)return!0}return!1}};var W1=class{components;log;routingTable;network;validators;queryManager;constructor(e,t){let{routingTable:n,network:i,validators:s,queryManager:o,lan:a}=t;this.components=e,this.routingTable=n,this.network=i,this.validators=s,this.queryManager=o,this.log=C(`libp2p:kad-dht:${a?"lan":"wan"}:peer-routing`)}async findPeerLocal(e){let t,n=await this.routingTable.find(e);if(n!=null){this.log("findPeerLocal found %p in routing table",e);try{t=await this.components.peerStore.get(n)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}}if(t==null)try{t=await this.components.peerStore.get(e)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(t!=null)return this.log("findPeerLocal found %p in peer store",e),{id:t.id,multiaddrs:t.addresses.map(i=>i.multiaddr),protocols:[]}}async*_getValueSingle(e,t,n={}){let i=new Bt($t.GET_VALUE,t,0);yield*this.network.sendRequest(e,i,n)}async*getPublicKeyFromNode(e,t={}){let n=VI(e);for await(let i of this._getValueSingle(e,n,t))if(yield i,i.name==="PEER_RESPONSE"&&i.record!=null){let s=await Zr(Rd.marshalPublicKey({bytes:i.record.value}));if(!s.equals(e))throw new w("public key does not match id","ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID");if(s.publicKey==null)throw new w("public key missing","ERR_PUBLIC_KEY_MISSING");yield Kf({from:e,value:s.publicKey},t)}throw new w(`Node not responding with its public key: ${e.toString()}`,"ERR_INVALID_RECORD")}async*findPeer(e,t={}){this.log("findPeer %p",e);let n=await this.findPeerLocal(e);if(n!=null){this.log("found local"),yield q1({from:this.components.peerId,peer:n},t);return}let i=this,s=async function*({peer:a,signal:c}){let u=new Bt($t.FIND_NODE,e.toBytes(),0);for await(let l of i.network.sendRequest(a,u,{...t,signal:c}))if(yield l,l.name==="PEER_RESPONSE"){let f=l.closer.find(h=>h.id.equals(e));f!=null&&(yield q1({from:l.from,peer:f},t))}},o=!1;for await(let a of this.queryManager.run(e.toBytes(),s,t))a.name==="FINAL_PEER"&&(o=!0),yield a;o||(yield $r({from:this.components.peerId,error:new w("Not found","ERR_NOT_FOUND")},t))}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);let n=await Co(e),i=this.routingTable.closestPeers(n),s=this,o=new G1(n,this.routingTable.kBucketSize);await Promise.all(i.map(async c=>{await o.add(c)}));let a=async function*({peer:c,signal:u}){s.log("closerPeersSingle %s from %p",U(e,"base32"),c);let l=new Bt($t.FIND_NODE,e,0);yield*s.network.sendRequest(c,l,{...t,signal:u})};for await(let c of this.queryManager.run(e,a,t))yield c,c.name==="PEER_RESPONSE"&&await Promise.all(c.closer.map(async u=>{await o.add(u.id)}));this.log("found %d peers close to %b",o.length,e);for(let c of o.peers)try{let u=await this.components.peerStore.get(c);yield q1({from:this.components.peerId,peer:{id:c,multiaddrs:u.addresses.map(({multiaddr:l})=>l),protocols:u.protocols}},t)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}}async*getValueOrPeers(e,t,n={}){for await(let i of this._getValueSingle(e,t,n)){if(i.name==="PEER_RESPONSE"&&i.record!=null)try{await this._verifyRecordOnline(i.record)}catch{let o="invalid record received, discarded";this.log(o),yield $r({from:i.from,error:new w(o,"ERR_INVALID_RECORD")},n);continue}yield i}}async _verifyRecordOnline(e){if(e.timeReceived==null)throw new w("invalid record received","ERR_INVALID_RECORD");await wu(this.validators,new vr(e.key,e.value,e.timeReceived))}async getCloserPeersOffline(e,t){let n=await Co(e),i=this.routingTable.closestPeers(n),s=[];for(let o of i)if(!o.equals(t))try{let a=await this.components.peerStore.get(o);s.push({id:o,multiaddrs:a.addresses.map(({multiaddr:c})=>c),protocols:a.protocols})}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}return s.length>0?this.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",s.length,e,t):this.log("getCloserPeersOffline could not find peer closer to %b than %p",e,t),s}};var WI=j(GI(),1);var Us=C("libp2p:kad-dht:providers"),Y1=class{components;cache;cleanupInterval;provideValidity;syncQueue;started;cleaner;constructor(e,t={}){let{cacheSize:n,cleanupInterval:i,provideValidity:s}=t;this.components=e,this.cleanupInterval=i??36e5,this.provideValidity=s??864e5,this.cache=(0,WI.default)(n??256),this.syncQueue=new kt({concurrency:1}),this.started=!1}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cleaner=setInterval(()=>{this._cleanup().catch(e=>{Us.error(e)})},this.cleanupInterval))}async stop(){this.started=!1,this.cleaner!=null&&(clearInterval(this.cleaner),this.cleaner=void 0)}async _cleanup(){await this.syncQueue.add(async()=>{let e=Date.now(),t=0,n=0,i=new Map,s=this.components.datastore.batch(),o=this.components.datastore.query({prefix:fy});for await(let a of o)try{let{cid:c,peerId:u}=YI(a.key),l=QI(a.value).getTime(),f=Date.now(),h=f-l,d=h>this.provideValidity;if(Us("comparing: %d - %d = %d > %d %s",f,l,h,this.provideValidity,d?"(expired)":""),d){n++,s.delete(a.key);let p=i.get(c)??new Set;p.add(u),i.set(c,p)}t++}catch(c){Us.error(c.message)}i.size>0?(Us("deleting %d / %d entries",n,t),await s.commit()):Us("nothing to delete");for(let[a,c]of i){let u=Vf(a),l=this.cache.get(u);if(l!=null){for(let f of c)l.delete(f);l.size===0?this.cache.remove(u):this.cache.set(u,l)}}Us("Cleanup successful (%dms)",Date.now()-e)})}async _getProvidersMap(e){let t=Vf(e),n=this.cache.get(t);return n==null&&(n=await FH(this.components.datastore,e),this.cache.set(t,n)),n}async addProvider(e,t){await this.syncQueue.add(async()=>{Us("%p provides %s",t,e);let n=await this._getProvidersMap(e);Us("loaded %s provs",n.size);let i=new Date;n.set(t.toString(),i);let s=Vf(e);this.cache.set(s,n),await UH(this.components.datastore,e,t,i)})}async getProviders(e){return this.syncQueue.add(async()=>(Us("get providers for %s",e),[...(await this._getProvidersMap(e)).keys()].map(n=>we(n))),{throwOnTimeout:!0})}};function Vf(r){let e=typeof r=="string"?r:U(r.multihash.bytes,"base32");return`${fy}/${e}`}async function UH(r,e,t,n){let i=[Vf(e),"/",t.toString()].join(""),s=new pt(i),o=Qr(n.getTime());await r.put(s,o)}function YI(r){let e=r.toString().split("/");if(e.length!==5)throw new Error(`incorrectly formatted provider entry key in datastore: ${r.toString()}`);return{cid:e[3],peerId:e[4]}}async function FH(r,e){let t=new Map,n=r.query({prefix:Vf(e)});for await(let i of n){let{peerId:s}=YI(i.key);t.set(s,QI(i.value))}return t}function QI(r){return new Date(on(r))}var Ha=j(Xr(),1);var KH=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");async function*XI(r){let{key:e,startingPeer:t,ourPeerId:n,signal:i,query:s,alpha:o,pathIndex:a,numPaths:c,cleanUp:u,queryFuncTimeout:l,log:f,peersSeen:h}=r,d=new kt({concurrency:o}),p=await Co(e);function m(g,y){if(g==null)return;h.add(g);let b=BigInt("0x"+U(Ls(y,p),"base16"));d.add(async()=>{let E=[i];l!=null&&E.push(AbortSignal.timeout(l));let _=er(E);try{for await(let x of s({key:e,peer:g,signal:_,pathIndex:a,numPaths:c})){if(_.aborted)return;if(x.name==="PEER_RESPONSE")for(let v of x.closer){if(h.has(v.id)){f("already seen %p in query",v.id);continue}if(n.equals(v.id)){f("not querying ourselves");continue}let R=await Ti(v.id);if(BigInt("0x"+U(Ls(R,p),"base16"))>b){f("skipping %p as they are not closer to %b than %p",v.id,e,g);continue}f("querying closer peer %p",v.id),m(v.id,R)}d.emit("completed",x)}}catch(x){if(!i.aborted)return $r({from:g,error:x},r)}finally{_.clear()}},{priority:KH-b}).catch(E=>{f.error(E)})}m(t,await Ti(t)),yield*VH(d,i,u,f)}async function*VH(r,e,t,n){let i=Le(),s=!0,o=[],a=()=>{s&&(n("clean up queue, results %d, queue size %d, pending tasks %d",o.length,r.size,r.pending),s=!1,r.clear(),o.splice(0,o.length))};for(r.on("completed",c=>{o.push(c),i.resolve()}),r.on("error",c=>{n("queue error",c),a(),i.reject(c)}),r.on("idle",()=>{n("queue idle"),s=!1,i.resolve()}),e.addEventListener("abort",()=>{n("abort queue");let c=s;a(),c&&i.reject(new w("Query aborted","ERR_QUERY_ABORTED"))}),t.addEventListener("cleanup",()=>{a(),i.resolve()});s;)for(await i.promise,i=Le();o.length>0;){let c=o.shift();c!=null&&(yield c)}yield*o}var X1=class{components;lan;disjointPaths;alpha;shutDownController;running;queries;metrics;routingTable;initialQuerySelfHasRun;constructor(e,t){let{lan:n=!1,disjointPaths:i=20,alpha:s=3}=t;this.components=e,this.disjointPaths=i??20,this.running=!1,this.alpha=s??3,this.lan=n,this.queries=0,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.shutDownController=new AbortController;try{Ha.setMaxListeners!=null&&(0,Ha.setMaxListeners)(1/0,this.shutDownController.signal)}catch{}}isStarted(){return this.running}async start(){this.running=!0,this.components.metrics!=null&&this.metrics==null&&(this.metrics={runningQueries:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_running_queries`),queryTime:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_query_time_seconds`)})}async stop(){this.running=!1,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");let i=this.metrics?.queryTime.timer();if(n.signal==null){n.signal=AbortSignal.timeout(3e4);try{Ha.setMaxListeners!=null&&(0,Ha.setMaxListeners)(1/0,n.signal)}catch{}}let s=er([this.shutDownController.signal,n.signal]);try{Ha.setMaxListeners!=null&&(0,Ha.setMaxListeners)(1/0,s)}catch{}let o=C(`libp2p:kad-dht:${this.lan?"lan":"wan"}:query:`+U(e,"base58btc")),a=Date.now(),c=new Ye;try{n.isSelfQuery!==!0&&this.initialQuerySelfHasRun!=null&&(o("waiting for initial query-self query before continuing"),await Promise.race([new Promise((p,m)=>{s.addEventListener("abort",()=>{m(new ai("Query was aborted before self-query ran"))})}),this.initialQuerySelfHasRun.promise]),this.initialQuerySelfHasRun=void 0),o("query:start"),this.queries++,this.metrics?.runningQueries.update(this.queries);let u=await Co(e),l=this.routingTable.closestPeers(u),f=l.slice(0,Math.min(this.disjointPaths,l.length));if(l.length===0){o.error("Running query with no peers");return}let h=new Hn,d=f.map((p,m)=>XI({key:e,startingPeer:p,ourPeerId:this.components.peerId,signal:s,query:t,pathIndex:m,numPaths:f.length,alpha:this.alpha,cleanUp:c,queryFuncTimeout:n.queryFuncTimeout,log:o,peersSeen:h,onProgress:n.onProgress}));for await(let p of Jt(...d))yield p,p.name==="QUERY_ERROR"&&o("error",p.error)}catch(u){if(!(!this.running&&u.code==="ERR_QUERY_ABORTED"))throw u}finally{s.clear(),this.queries--,this.metrics?.runningQueries.update(this.queries),i?.(),c.dispatchEvent(new nt("cleanup")),o("query:done in %dms",Date.now()-a)}}};var wy=j(Xr(),1);function zH(r){return r[Symbol.asyncIterator]!=null}function $H(r){if(zH(r))return(async()=>{let e=0;for await(let t of r)e++;return e})();{let e=0;for(let t of r)e++;return e}}var j1=$H;var Z1=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},yy=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},jI=r=>globalThis.DOMException===void 0?new yy(r):new DOMException(r),ZI=r=>{let e=r.reason===void 0?jI("This operation was aborted."):r.reason;return e instanceof Error?e:jI(e)};function by(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(ZI(h)),h.addEventListener("abort",()=>{l(ZI(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new Z1;o=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},c}var HH=r=>{let e=r.on||r.addListener||r.addEventListener,t=r.off||r.removeListener||r.removeEventListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function GH(r,e,t){let n,i=new Promise((s,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=HH(r),f=(...d)=>{let p=t.multiArgs?d:d[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},h=d=>{n(),o(d)};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)l(d,h)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)u(d,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(i.cancel=n,typeof t.timeout=="number"){let s=by(i,{milliseconds:t.timeout});return s.cancel=n,s}return i}function JI(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=GH(r,e,t),i=n.then(s=>s[0]);return i.cancel=n.cancel,i}var J1=class{log;components;peerRouting;routingTable;count;interval;initialInterval;queryTimeout;started;timeoutId;controller;initialQuerySelfHasRun;querySelfPromise;constructor(e,t){let{peerRouting:n,lan:i,count:s,interval:o,queryTimeout:a,routingTable:c}=t;this.components=e,this.log=C(`libp2p:kad-dht:${i?"lan":"wan"}:query-self`),this.started=!1,this.peerRouting=n,this.routingTable=c,this.count=s??20,this.interval=o??3e5,this.initialInterval=t.initialInterval??1e3,this.queryTimeout=a??5e3,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun}isStarted(){return this.started}start(){this.started||(this.started=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query",e)})},this.initialInterval))}stop(){this.started=!1,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.controller!=null&&this.controller.abort()}async querySelf(){if(!this.started){this.log("skip self-query because we are not started");return}if(this.querySelfPromise!=null)return this.log("joining existing self query"),this.querySelfPromise.promise;if(this.querySelfPromise=Le(),this.routingTable.size===0&&await JI(this.routingTable,"peer:add"),this.started){this.controller=new AbortController;let e=er([this.controller.signal,AbortSignal.timeout(this.queryTimeout)]);try{wy.setMaxListeners!=null&&(0,wy.setMaxListeners)(1/0,e)}catch{}try{this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);let t=await Me(this.peerRouting.getClosestPeers(this.components.peerId.toBytes(),{signal:e,isSelfQuery:!0}),n=>Ys(n,this.count),async n=>j1(n));this.log("self-query ran successfully - found %d peers",t),this.initialQuerySelfHasRun!=null&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}catch(t){this.log.error("self-query error",t)}finally{e.clear()}}this.querySelfPromise.resolve(),this.querySelfPromise=void 0,this.started&&(this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query",e)})},this.interval))}};function eA(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0,n=r.length;t(t.vectorClock??0)?e:t}static distance(e,t){let n=0,i=0,s=Math.min(e.length,t.length),o=Math.max(e.length,t.length);for(;i=0?(this._update(n,i,e),this):n.contacts.length0&&n.length({distance:this.distance(i.id,e),contact:i})).sort((i,s)=>i.distance-s.distance).slice(0,t).map(i=>i.contact)}count(){let e=0;for(let t=[this.root];t.length>0;){let n=t.pop();n!=null&&(n.contacts===null?t.push(n.right,n.left):e+=n.contacts.length)}return e}_determineNode(e,t,n){let i=n>>3,s=n%8;return t.length<=i&&s!==0?e.left:t[i]&1<<7-s?e.right:e.left}get(e){qf("id",e);let t=0,n=this.root;for(;n.contacts===null;)n=this._determineNode(n,e,t++);let i=this._indexOf(n,e);return i>=0?n.contacts[i]:void 0}_indexOf(e,t){for(let n=0;n=0){let s=n.contacts.splice(i,1)[0];this.safeDispatchEvent("removed",{detail:s})}return this}_split(e,t){e.left=Ey(),e.right=Ey();for(let s of e.contacts)this._determineNode(e,s.id,t).contacts.push(s);e.contacts=null;let n=this._determineNode(e,this.localNodeId,t),i=e.left===n?e.right:e.left;i.dontSplit=!0}toArray(){let e=[];for(let t=[this.root];t.length>0;){let n=t.pop();n!=null&&(n.contacts===null?t.push(n.right,n.left):e=e.concat(n.contacts))}return e}*toIterable(){for(let e=[this.root];e.length>0;){let t=e.pop();t!=null&&(t.contacts===null?e.push(t.right,t.left):yield*t.contacts)}}_update(e,t,n){if(!eA(e.contacts[t].id,n.id))throw new Error("wrong index for _update");let i=e.contacts[t],s=this.arbiter(i,n);s===i&&i!==n||(e.contacts.splice(t,1),e.contacts.push(s),this.safeDispatchEvent("updated",{detail:{incumbent:i,selection:s}}))}};var XH="kad-close",jH=50,tA=20,ZH=1e4,JH=10,tp=class extends Ye{kBucketSize;kb;pingQueue;log;components;lan;pingTimeout;pingConcurrency;running;protocol;tagName;tagValue;metrics;constructor(e,t){super();let{kBucketSize:n,pingTimeout:i,lan:s,pingConcurrency:o,protocol:a,tagName:c,tagValue:u}=t;this.components=e,this.log=C(`libp2p:kad-dht:${s?"lan":"wan"}:routing-table`),this.kBucketSize=n??tA,this.pingTimeout=i??ZH,this.pingConcurrency=o??JH,this.lan=s,this.running=!1,this.protocol=a,this.tagName=c??XH,this.tagValue=u??jH;let l=()=>{this.metrics?.pingQueueSize.update(this.pingQueue.size),this.metrics?.pingRunning.update(this.pingQueue.pending)};this.pingQueue=new kt({concurrency:this.pingConcurrency}),this.pingQueue.addListener("add",l),this.pingQueue.addListener("next",l),this._onPing=this._onPing.bind(this)}isStarted(){return this.running}async start(){this.running=!0,this.components.metrics!=null&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_routing_table_size`),pingQueueSize:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_ping_queue_size`),pingRunning:this.components.metrics.registerMetric(`libp2p_kad_dht_${this.lan?"lan":"wan"}_ping_running`)});let e=new ep({localNodeId:await Ti(this.components.peerId),numberOfNodesPerKBucket:this.kBucketSize,numberOfNodesToPing:1});this.kb=e,e.addEventListener("ping",this._onPing),this._tagPeers(e)}async stop(){this.running=!1,this.pingQueue.clear(),this.kb=void 0}_tagPeers(e){let t=new Hn,n=$I(()=>{let i=new Hn(e.closest(e.localNodeId,tA).map(a=>a.peer)),s=i.difference(t),o=t.difference(i);Promise.resolve().then(async()=>{for(let a of s)await this.components.peerStore.merge(a,{tags:{[this.tagName]:{value:this.tagValue}}});for(let a of o)await this.components.peerStore.merge(a,{tags:{[this.tagName]:void 0}})}).catch(a=>{this.log.error("Could not update peer tags",a)}),t=i});e.addEventListener("added",i=>{n(),this.safeDispatchEvent("peer:add",{detail:i.detail.peer})}),e.addEventListener("removed",i=>{n(),this.safeDispatchEvent("peer:remove",{detail:i.detail.peer})})}_onPing(e){let{oldContacts:t,newContact:n}=e.detail;this.pingQueue.add(async()=>{if(!this.running)return;let i=0;try{await Promise.all(t.map(async s=>{try{let o={signal:AbortSignal.timeout(this.pingTimeout)};this.log("pinging old contact %p",s.peer),await(await(await this.components.connectionManager.openConnection(s.peer,o)).newStream(this.protocol,o)).close(),i++}catch(o){this.running&&this.kb!=null&&(this.log.error("could not ping peer %p",s.peer,o),this.log("evicting old contact after ping failed %p",s.peer),this.kb.remove(s.id))}finally{this.metrics?.routingTableSize.update(this.size)}})),this.running&&i{this.log.error("could not process k-bucket ping event",i)})}get size(){return this.kb==null?0:this.kb.count()}async find(e){let t=await Ti(e),n=this.closestPeer(t);if(n!=null&&e.equals(n))return n}closestPeer(e){let t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e,t=this.kBucketSize){return this.kb==null?[]:this.kb.closest(e,t).map(i=>i.peer)}async add(e){if(this.kb==null)throw new Error("RoutingTable is not started");let t=await Ti(e);this.kb.add({id:t,peer:e}),this.log("added %p with kad id %b",e,t),this.metrics?.routingTableSize.update(this.size)}async remove(e){if(this.kb==null)throw new Error("RoutingTable is not started");let t=await Ti(e);this.kb.remove(t),this.metrics?.routingTableSize.update(this.size)}};var rA=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];var rp=15,np=class{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e){let{peerRouting:t,routingTable:n,refreshInterval:i,refreshQueryTimeout:s,lan:o}=e;this.log=C(`libp2p:kad-dht:${o?"lan":"wan"}:routing-table:refresh`),this.peerRouting=t,this.routingTable=n,this.refreshInterval=i??3e5,this.refreshQueryTimeout=s??3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async start(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){this.refreshTimeoutId!=null&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1){this.log("refreshing routing table");let t=this._maxCommonPrefix(),n=this._getTrackedCommonPrefixLengthsForRefresh(t);this.log(`max common prefix length ${t}`),this.log(`tracked CPLs [ ${n.map(i=>i.toISOString()).join(", ")} ]`),Promise.all(n.map(async(i,s)=>{try{if(await this._refreshCommonPrefixLength(s,i,e),this._numPeersForCpl(t)===0){let o=Math.min(2*(s+1),n.length-1);for(let a=s+1;a{this.log.error(i)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),this.refreshTimeoutId.unref!=null&&this.refreshTimeoutId.unref()}).catch(i=>{this.log.error(i)})}async _refreshCommonPrefixLength(e,t,n){if(!n&&t.getTime()>Date.now()-this.refreshInterval){this.log("not running refresh for cpl %s as time since last refresh not above interval",e);return}let i=await this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);let s=await j1(this.peerRouting.getClosestPeers(i.toBytes(),{signal:AbortSignal.timeout(this.refreshQueryTimeout)}));this.log(`found ${s} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}_getTrackedCommonPrefixLengthsForRefresh(e){e>rp&&(e=rp);let t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}async _generateRandomPeerId(e){if(this.routingTable.kb==null)throw new Error("Routing table not started");let t=zn(2),n=(t[1]<<8)+t[0],i=await this._makePeerId(this.routingTable.kb.localNodeId,n,e);return Ot(i)}async _makePeerId(e,t,n){if(n>rp)throw new Error(`Cannot generate peer ID for common prefix length greater than ${rp}`);let o=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1)^32768>>n,a=65535<<16-(n+1),c=o&a|t&~a,u=rA[c],l=new ArrayBuffer(34),f=new DataView(l,0,l.byteLength);return f.setUint8(0,Ke.code),f.setUint8(1,32),f.setUint32(2,u,!1),new Uint8Array(f.buffer,f.byteOffset,f.byteLength)}_maxCommonPrefix(){let e=0;for(let t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(let n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(this.routingTable.kb!=null)for(let{id:e}of this.routingTable.kb.toIterable()){let t=Ls(this.routingTable.kb.localNodeId,e),n=0;for(let i of t)if(i===0)n++;else break;yield n}}};var zf=C("libp2p:kad-dht:rpc:handlers:add-provider"),ip=class{providers;constructor(e){let{providers:t}=e;this.providers=t}async handle(e,t){if(zf("start"),t.key==null||t.key.length===0)throw new w("Missing key","ERR_MISSING_KEY");let n;try{n=Ne.decode(t.key)}catch{throw new w("Invalid CID","ERR_INVALID_CID")}(t.providerPeers==null||t.providerPeers.length===0)&&zf.error("no providers found in message"),await Promise.all(t.providerPeers.map(async i=>{if(!i.id.equals(e)){zf("invalid provider peer %p from %p",i.id,e);return}if(i.multiaddrs.length<1){zf("no valid addresses for provider %p. Ignore",e);return}zf("received provider %p for %s (addrs %s)",e,n,i.multiaddrs.map(s=>s.toString())),await this.providers.addProvider(n,i.id)}))}};var nA=C("libp2p:kad-dht:rpc:handlers:find-node"),sp=class{peerRouting;lan;components;constructor(e,t){let{peerRouting:n,lan:i}=t;this.components=e,this.peerRouting=n,this.lan=!!i}async handle(e,t){nA("incoming request from %p for peers closer to %b",e,t.key);let n=[];fe(this.components.peerId.toBytes(),t.key)?n=[{id:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(s=>s.decapsulateCode(le("p2p").code)),protocols:[]}]:n=await this.peerRouting.getCloserPeersOffline(t.key,e),n=n.map(this.lan?xu:Eu).filter(({multiaddrs:s})=>s.length);let i=new Bt(t.type,new Uint8Array(0),t.clusterLevel);return n.length>0?i.closerPeers=n:nA("could not find any peers closer to %b than %p",t.key,e),i}};var iA=C("libp2p:kad-dht:rpc:handlers:get-providers"),op=class{components;peerRouting;providers;lan;constructor(e,t){let{peerRouting:n,providers:i,lan:s}=t;this.components=e,this.peerRouting=n,this.providers=i,this.lan=!!s}async handle(e,t){let n;try{n=Ne.decode(t.key)}catch{throw new w("Invalid CID","ERR_INVALID_CID")}iA("%p asking for providers for %s",e,n);let[i,s]=await Promise.all([this.providers.getProviders(n),this.peerRouting.getCloserPeersOffline(t.key,e)]),o=await this._getPeers(i),a=await this._getPeers(s.map(({id:u})=>u)),c=new Bt(t.type,t.key,t.clusterLevel);return o.length>0&&(c.providerPeers=o),a.length>0&&(c.closerPeers=a),iA("got %s providers %s closerPeers",o.length,a.length),c}async _getAddresses(e){return[]}async _getPeers(e){let t=[],n=this.lan?xu:Eu;for(let i of e)try{let s=await this.components.peerStore.get(i),o=n({id:i,multiaddrs:s.addresses.map(({multiaddr:a})=>a),protocols:s.protocols});o.multiaddrs.length>0&&t.push(o)}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}return t}};var _u=C("libp2p:kad-dht:rpc:handlers:get-value"),ap=class{components;peerRouting;constructor(e,t){let{peerRouting:n}=t;this.components=e,this.peerRouting=n}async handle(e,t){let n=t.key;if(_u("%p asked for key %b",e,n),n==null||n.length===0)throw new w("Invalid key","ERR_INVALID_KEY");let i=new Bt($t.GET_VALUE,n,t.clusterLevel);if(qI(n)){_u("is public key");let a=zI(n),c;try{let u=await this.components.peerStore.get(a);if(u.id.publicKey==null)throw new w("No public key found in key book","ERR_NOT_FOUND");c=u.id.publicKey}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(c!=null)return _u("returning found public key"),i.record=new vr(n,c,new Date),i}let[s,o]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getCloserPeersOffline(t.key,e)]);return s!=null&&(_u("had record for %b in local datastore",n),i.record=s),o.length>0&&(_u("had %s closer peers in routing table",o.length),i.closerPeers=o),i}async _checkLocalDatastore(e){_u("checkLocalDatastore looking for %b",e);let t=Ms(e),n;try{n=await this.components.datastore.get(t)}catch(s){if(s.code==="ERR_NOT_FOUND")return;throw s}let i=vr.deserialize(n);if(i==null)throw new w("Invalid record","ERR_INVALID_RECORD");if(i.timeReceived==null||Date.now()-i.timeReceived.getTime()>1296e5){await this.components.datastore.delete(t);return}return i}};var nG=C("libp2p:kad-dht:rpc:handlers:ping"),cp=class{async handle(e,t){return nG("ping from %p",e),t}};var up=class{log;components;validators;constructor(e,t){let{validators:n}=t;this.components=e,this.log=C("libp2p:kad-dht:rpc:handlers:put-value"),this.validators=n}async handle(e,t){let n=t.key;this.log("%p asked us to store value for key %b",e,n);let i=t.record;if(i==null){let s=`Empty record from: ${e.toString()}`;throw this.log.error(s),new w(s,"ERR_EMPTY_RECORD")}try{await wu(this.validators,i),i.timeReceived=new Date;let s=Ms(i.key);await this.components.datastore.put(s,i.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,s)}catch(s){this.log("did not put record for key %b into datastore %o",n,s)}return t}};var lp=class{handlers;routingTable;log;constructor(e,t){let{providers:n,peerRouting:i,validators:s,lan:o}=t;this.log=C("libp2p:kad-dht:rpc"),this.routingTable=t.routingTable,this.handlers={[$t.GET_VALUE]:new ap(e,{peerRouting:i}),[$t.PUT_VALUE]:new up(e,{validators:s}),[$t.FIND_NODE]:new sp(e,{peerRouting:i,lan:o}),[$t.ADD_PROVIDER]:new ip({providers:n}),[$t.GET_PROVIDERS]:new op(e,{peerRouting:i,providers:n,lan:o}),[$t.PING]:new cp}}async handleMessage(e,t){try{await this.routingTable.add(e)}catch(i){this.log.error("Failed to update the kbucket store",i)}let n=this.handlers[t.type];if(n==null){this.log.error(`no handler found for message type: ${t.type}`);return}return n.handle(e,t)}onIncomingStream(e){Promise.resolve().then(async()=>{let{stream:t,connection:n}=e,i=n.remotePeer;try{await this.routingTable.add(i)}catch(o){this.log.error(o)}let s=this;await Me(t,o=>Yt(o),async function*(o){for await(let a of o){let c=Bt.deserialize(a);s.log("incoming %s from %p",c.type,i);let u=await s.handleMessage(i,c);u!=null&&(yield u.serialize())}},o=>Kt(o),t)}).catch(t=>{this.log.error(t)})}};var fp=class extends Ye{log;components;protocol;running;registrarId;constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=C(`libp2p:kad-dht:topology-listener:${i?"lan":"wan"}`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.registrarId=await this.components.registrar.register(this.protocol,{onConnect:e=>{this.log("observed peer %p with protocol %s",e,this.protocol),this.dispatchEvent(new nt("peer",{detail:e}))}}))}async stop(){this.running=!1,this.registrarId!=null&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}};var iG=32,sG=64,$f=class extends Ye{protocol;routingTable;providers;network;peerRouting;components;log;running;kBucketSize;clientMode;lan;validators;selectors;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;constructor(e,t){super();let{kBucketSize:n,clientMode:i,validators:s,selectors:o,querySelfInterval:a,lan:c,protocolPrefix:u,pingTimeout:l,pingConcurrency:f,maxInboundStreams:h,maxOutboundStreams:d,providers:p}=t;this.running=!1,this.components=e,this.lan=!!c,this.log=C(`libp2p:kad-dht:${c===!0?"lan":"wan"}`),this.protocol=`${u??DI}${c===!0?TI:""}${CI}`,this.kBucketSize=n??20,this.clientMode=i??!0,this.maxInboundStreams=h??iG,this.maxOutboundStreams=d??sG,this.routingTable=new tp(e,{kBucketSize:n,lan:this.lan,pingTimeout:l,pingConcurrency:f,protocol:this.protocol}),this.providers=new Y1(e,p??{}),this.validators={...KI,...s},this.selectors={...FI,...o},this.network=new H1(e,{protocol:this.protocol,lan:this.lan});let m=Le();t.allowQueryWithZeroPeers===!0&&m.resolve(),this.queryManager=new X1(e,{disjointPaths:Math.ceil(this.kBucketSize/2),lan:c,initialQuerySelfHasRun:m,routingTable:this.routingTable}),this.peerRouting=new W1(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,lan:this.lan}),this.contentFetching=new z1(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,lan:this.lan}),this.contentRouting=new $1(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,lan:this.lan}),this.routingTableRefresh=new np({peerRouting:this.peerRouting,routingTable:this.routingTable,lan:this.lan}),this.rpc=new lp(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,lan:this.lan}),this.topologyListener=new fp(e,{protocol:this.protocol,lan:this.lan}),this.querySelf=new J1(e,{peerRouting:this.peerRouting,interval:a,initialInterval:t.initialQuerySelfInterval,lan:this.lan,initialQuerySelfHasRun:m,routingTable:this.routingTable}),this.network.addEventListener("peer",g=>{let y=g.detail;this.onPeerConnect(y).catch(b=>{this.log.error("could not add %p to routing table",y.id,b)}),this.dispatchEvent(new nt("peer",{detail:y}))}),this.topologyListener.addEventListener("peer",g=>{let y=g.detail;Promise.resolve().then(async()=>{let b=await this.components.peerStore.get(y),E={id:y,multiaddrs:b.addresses.map(({multiaddr:_})=>_),protocols:b.protocols};await this.onPeerConnect(E)}).catch(b=>{this.log.error("could not add %p to routing table",y,b)})})}async onPeerConnect(e){if(this.log("peer %p connected with protocols",e.id,e.protocols),this.lan?e=xu(e):e=Eu(e),e.multiaddrs.length===0){this.log("ignoring %p as they do not have any %s addresses in %s",e.id,this.lan?"private":"public",e.multiaddrs.map(t=>t.toString()));return}try{await this.routingTable.add(e.id)}catch(t){this.log.error("could not add %p to routing table",e.id,t)}}isStarted(){return this.running}async getMode(){return this.clientMode?"client":"server"}async setMode(e){await this.components.registrar.unhandle(this.protocol),e==="client"?(this.log("enabling client mode"),this.clientMode=!0):(this.log("enabling server mode"),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}))}async start(){this.running=!0,await this.setMode(this.clientMode?"client":"server"),await Promise.all([this.providers.start(),this.queryManager.start(),this.network.start(),this.routingTable.start(),this.topologyListener.start()]),this.querySelf.start(),await this.routingTableRefresh.start()}async stop(){this.running=!1,this.querySelf.stop(),await Promise.all([this.providers.stop(),this.queryManager.stop(),this.network.stop(),this.routingTable.stop(),this.routingTableRefresh.stop(),this.topologyListener.stop()])}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(){this.routingTableRefresh.refreshTable(!0)}};var Su=C("libp2p:kad-dht"),xy=class{dht;constructor(e){this.dht=e}async provide(e,t={}){await Wr(this.dht.provide(e,t))}async*findProviders(e,t={}){for await(let n of this.dht.findProviders(e,t))n.name==="PROVIDER"&&(yield*n.providers)}async put(e,t,n){await Wr(this.dht.put(e,t,n))}async get(e,t){for await(let n of this.dht.get(e,t))if(n.name==="VALUE")return n.value;throw new w("Not found","ERR_NOT_FOUND")}},vy=class{dht;constructor(e){this.dht=e}async findPeer(e,t={}){for await(let n of this.dht.findPeer(e,t))if(n.name==="FINAL_PEER")return n.peer;throw new w("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){for await(let n of this.dht.getClosestPeers(e,t))n.name==="FINAL_PEER"&&(yield n.peer)}},oG=290,aG=54,cG=55,uG=56,lG=4,fG=41;function hG(r){let e=r.stringTuples();for(let t of e)if(t[0]===oG)return!1;if(e[0][0]===aG||e[0][0]===cG||e[0][0]===uG)return Su("%m is public %s",r,!0),!0;if(e[0][0]===lG||e[0][0]===fG){let t=Jr(`${e[0][1]}`),n=t==null||!t;return Su("%m is public %s",r,n),n}return!1}var hp=class extends Ye{wan;lan;components;contentRouting;peerRouting;constructor(e,t={}){super(),this.components=e,this.wan=new $f(e,{protocolPrefix:"/ipfs",...t,lan:!1}),this.lan=new $f(e,{protocolPrefix:"/ipfs",...t,clientMode:!1,lan:!0}),this.contentRouting=new xy(this),this.peerRouting=new vy(this),this.wan.addEventListener("peer",n=>{this.dispatchEvent(new nt("peer",{detail:n.detail}))}),this.lan.addEventListener("peer",n=>{this.dispatchEvent(new nt("peer",{detail:n.detail}))}),t.clientMode==null&&e.events.addEventListener("self:peer:update",n=>{Su("received update of self-peer info");let i=n.detail.peer.addresses.some(({multiaddr:s})=>{let o=hG(s);return Su("%m is public %s",s,o),o});this.getMode().then(async s=>{i&&s==="client"?await this.setMode("server"):s==="server"&&!i&&await this.setMode("client")}).catch(s=>{Su.error("error setting dht server mode",s)})})}[Symbol.toStringTag]="@libp2p/dual-kad-dht";get[cf](){return this.contentRouting}get[uf](){return this.peerRouting}get[Ta](){return this}isStarted(){return this.wan.isStarted()&&this.lan.isStarted()}async getMode(){return this.wan.getMode()}async setMode(e){await this.wan.setMode(e)}async start(){await Promise.all([this.lan.start(),this.wan.start()])}async stop(){await Promise.all([this.lan.stop(),this.wan.stop()])}async*put(e,t,n={}){for await(let i of Jt(this.lan.put(e,t,n),this.wan.put(e,t,n)))yield i}async*get(e,t={}){let n=!1,i=!1;for await(let s of Jt(this.lan.get(e,t),this.wan.get(e,t)))yield s,s.name==="DIAL_PEER"&&(n=!0),s.name==="VALUE"&&(n=!0,s.value!=null&&(i=!0)),s.name==="SEND_QUERY"&&(n=!0);if(!n)throw new w("No peers found in routing table!","ERR_NO_PEERS_IN_ROUTING_TABLE");i||(yield $r({from:this.components.peerId,error:new w("Not found","ERR_NOT_FOUND")},t))}async*provide(e,t={}){let n=0,i=0,s=[],o=[this.lan];await this.wan.getMode()==="server"&&o.push(this.wan);for await(let a of Jt(...o.map(c=>c.provide(e,t))))yield a,a.name==="SEND_QUERY"&&n++,a.name==="QUERY_ERROR"&&s.push(a.error),a.name==="PEER_RESPONSE"&&a.messageName==="ADD_PROVIDER"&&(Su("sent provider record for %s to %p",e,a.from),i++);if(i===0)throw s.length>0?new w(`Failed to provide to ${s.length} of ${n} peers`,"ERR_PROVIDES_FAILED",{errors:s}):new w("Failed to provide - no peers found","ERR_PROVIDES_FAILED")}async*findProviders(e,t={}){yield*Jt(this.lan.findProviders(e,t),this.wan.findProviders(e,t))}async*findPeer(e,t={}){let n=!1;for await(let i of Jt(this.lan.findPeer(e,t),this.wan.findPeer(e,t)))yield i,(i.name==="SEND_QUERY"||i.name==="FINAL_PEER")&&(n=!0);if(!n)throw new w("Peer lookup failed","ERR_LOOKUP_FAILED")}async*getClosestPeers(e,t={}){yield*Jt(this.lan.getClosestPeers(e,t),this.wan.getClosestPeers(e,t))}async refreshRoutingTable(){await Promise.all([this.lan.refreshRoutingTable(),this.wan.refreshRoutingTable()])}};var sA;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(sA||(sA={}));var oA;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(oA||(oA={}));function aA(r){return e=>new hp(e,r)}var yA=j(ug(),1);var Fe;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(Fe||(Fe={}));var Hf=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),_y=Object.freeze({NEW_STREAM:Fe.NEW_STREAM,MESSAGE:Fe.MESSAGE_INITIATOR,CLOSE:Fe.CLOSE_INITIATOR,RESET:Fe.RESET_INITIATOR}),cA=Object.freeze({MESSAGE:Fe.MESSAGE_RECEIVER,CLOSE:Fe.CLOSE_RECEIVER,RESET:Fe.RESET_RECEIVER});var Sy=1<<20,dG=4<<20,dp=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Sy,t=dG){this._buffer=new Te,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(u){if(u.code==="ERR_MSG_TOO_BIG")throw u;break}let{id:n,type:i,length:s,offset:o}=this._headerInfo;if(this._buffer.length-othis._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:o,offset:n+s,length:i}}},pG=128,uA=127;function lA(r,e=0){let t=0,n=0,i=e,s,o=r.length;do{if(i>=o||n>49)throw e=0,new RangeError("Could not decode varint");s=r.get(i++),t+=n<28?(s&uA)<=pG);return e=i-e,{value:t,offset:e}}function mG(r){return r[Symbol.asyncIterator]!=null}var pp=1024*1024,fA=(r,e)=>{e.append(r)};function gG(r,e){return mG(r)?async function*(){let t=new Te,n=!1,i=Le(),s=Number(e?.size??pp);if((isNaN(s)||s===0||s<0)&&(s=pp),s!==Math.round(s))throw new Error("Batch size must be an integer");let o=e?.yieldAfter??0,a=e?.serialize??fA;for(Promise.resolve().then(async()=>{try{let c;for await(let u of r){if(a(u,t),t.byteLength>=s){clearTimeout(c),i.resolve();continue}c=setTimeout(()=>{i.resolve()},o)}clearTimeout(c),i.resolve()}catch(c){i.reject(c)}finally{n=!0}});!n;)if(await i.promise,i=Le(),t.byteLength>0){let c=t;t=new Te,yield c.subarray()}}():function*(){let t=new Te,n=Number(e?.size??pp);if((isNaN(n)||n===0||n<0)&&(n=pp),n!==Math.round(n))throw new Error("Batch size must be an integer");let i=e?.serialize??fA;for(let s of r)i(s,t),t.byteLength>=n&&(yield t.subarray(0,n),t.consume(n));t.byteLength>0&&(yield t.subarray())}()}var hA=gG;function Ry(r){return new Uint8Array(r)}var Iy=10*1024,Ay=class{_pool;_poolOffset;constructor(){this._pool=Ry(Iy),this._poolOffset=0}write(e,t){let n=this._pool,i=this._poolOffset;Qr(e.id<<3|e.type,n,i),i+=sr(e.id<<3|e.type),(e.type===Fe.NEW_STREAM||e.type===Fe.MESSAGE_INITIATOR||e.type===Fe.MESSAGE_RECEIVER)&&e.data!=null?(Qr(e.data.length,n,i),i+=sr(e.data.length)):(Qr(0,n,i),i+=sr(0));let s=n.subarray(this._poolOffset,i);Iy-i<100?(this._pool=Ry(Iy),this._poolOffset=0):this._poolOffset=i,t.append(s),(e.type===Fe.NEW_STREAM||e.type===Fe.MESSAGE_INITIATOR||e.type===Fe.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},dA=new Ay;async function*pA(r,e=0){if(e==null||e===0){for await(let t of r){let n=new Te;for(let i of t)dA.write(i,n);yield n.subarray()}return}yield*hA(r,{size:e,serialize:(t,n)=>{for(let i of t)dA.write(i,n)}})}var Ty=class extends Io{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?_y:cA,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:_y.NEW_STREAM,data:new Te(G(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}};function mA(r){let{id:e,name:t,send:n,onEnd:i,type:s="initiator",maxMsgSize:o=Sy}=r;return new Ty({id:s==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:s==="initiator"?"outbound":"inbound",maxDataSize:o,onEnd:i,send:n,log:C(`libp2p:mplex:stream:${s}:${e}`)})}var xn=C("libp2p:mplex"),yG=1024,bG=1024,wG=1024*1024*4,EG=5,xG=500;function gA(r){let e={...r,type:`${Hf[r.type]} (${r.type})`};return r.type===Fe.NEW_STREAM&&(e.data=U(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===Fe.MESSAGE_INITIATOR||r.type===Fe.MESSAGE_RECEIVER)&&(e.data=U(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var mp=class{protocol="/mplex/6.7.0";sink;source;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;constructor(e){e=e??{},this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=e,this.closeTimeout=e.closeTimeout??xG,this.sink=this._createSink(),this._source=F6({objectMode:!0,onEnd:()=>{for(let t of this._streams.initiators.values())t.destroy();for(let t of this._streams.receivers.values())t.destroy()}}),this.source=Me(this._source,t=>pA(t,this._init.minSendBytes)),this.closeController=new AbortController,this.rateLimiter=new yA.RateLimiterMemory({points:e.disconnectThreshold??EG,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let n=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:n})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(n){this.abort(n)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:n}=e,i=this._streams.receivers;return this._newStream({id:t,name:n,type:"receiver",registry:i})}_newStream(e){let{id:t,name:n,type:i,registry:s}=e;if(xn("new %s stream %s",i,t),i==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??bG))throw new w("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${i} stream ${t} already exists!`);let c=mA({id:t,name:n,send:async u=>{xn.enabled&&xn.trace("%s stream %s send",i,t,gA(u)),this._source.push(u)},type:i,onEnd:()=>{xn("%s stream with id %s and protocol %s ended",i,t,c.protocol),s.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize});return s.set(t,c),c}_createSink(){return async t=>{try{t=Er(t,this.closeController.signal,{returnOnAbort:!0});let n=new dp(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let i of t)for(let s of n.write(i))await this._handleIncoming(s);this._source.end()}catch(n){xn("error in sink",n),this._source.end(n)}}}async _handleIncoming(e){let{id:t,type:n}=e;if(xn.enabled&&xn.trace("incoming message",gA(e)),e.type===Fe.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??yG)){xn("too many inbound streams open"),this._source.push({id:t,type:Fe.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{xn("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:U(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let s=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(s==null){xn("missing stream %s for message type %s",t,Hf[n]);try{await this.rateLimiter.consume("missing-stream",1)}catch{xn("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}let o=this._init.maxStreamBufferSize??wG;try{switch(n){case Fe.MESSAGE_INITIATOR:case Fe.MESSAGE_RECEIVER:if(s.sourceReadableLength()>o)throw this._source.push({id:e.id,type:n===Fe.MESSAGE_INITIATOR?Fe.RESET_RECEIVER:Fe.RESET_INITIATOR}),new w("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");s.sourcePush(e.data);break;case Fe.CLOSE_INITIATOR:case Fe.CLOSE_RECEIVER:s.remoteCloseWrite();break;case Fe.RESET_INITIATOR:case Fe.RESET_RECEIVER:s.reset();break;default:xn("unknown message type %s",n)}}catch(a){xn.error("error while processing message",a),s.abort(a)}}};var Dy=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}createStreamMuxer(e={}){return new mp({...e,...this._init})}};function bA(r={}){return()=>new Dy(r)}var vn;(function(r){r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",r.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",r.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(vn||(vn={}));var Po=class extends w{constructor(e,t){super(`WebRTC transport error: ${e}`,t??""),this.name="WebRTCTransportError"}};var Cy=class extends Po{constructor(e,t){super(`[stream: ${e}] data channel error: ${t}`,vn.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function Ly(r,e){return new Cy(r,e)}var Py=class extends Po{constructor(e){super(`There was a problem with the Multiaddr which was passed in: ${e}`,vn.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function gp(r){return new Py(r)}var ky=class extends Po{constructor(e){super(`There was a problem with a provided argument: ${e}`,vn.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function Gf(r){return new ky(r)}var Ny=class extends Po{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`,vn.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function My(r,e){return new Ny(r,e)}var Oy=class extends Po{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`,vn.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function wA(r){return new Oy(r)}var By=class extends Po{constructor(e){super(`unsupported hash algorithm: ${e}`,vn.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function EA(r){return new By(r)}var xA=function(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new IG:typeof navigator<"u"?SA(navigator.userAgent):kG()}function CG(r){return r!==""&&DG.reduce(function(e,t){var n=t[0],i=t[1];if(e)return e;var s=i.exec(r);return!!s&&[n,s]},!1)}function SA(r){var e=CG(r);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new RG;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{};var AA=C("libp2p:webrtc:connection"),Ga=class{peerConnection;remoteAddr;timeline;metrics;source=yp();sink=bp;constructor(e){this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection,this.peerConnection.onconnectionstatechange=()=>{(this.peerConnection.connectionState==="closed"||this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed")&&(this.timeline.close=Date.now())}}async close(e){AA.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(e){AA.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Ru=globalThis.RTCPeerConnection,Uy=globalThis.RTCSessionDescription,TA=globalThis.RTCIceCandidate;function _r(r,e){let t=Cf(r,e),n={read:async(i,s)=>{let o=await t.read(s);return i.decode(o)},write:async(i,s,o)=>{await t.write(s.encode(i),o)},pb:i=>({read:async s=>n.read(i,s),write:async(s,o)=>n.write(s,i,o),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var Iu=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Fy=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},DA=r=>globalThis.DOMException===void 0?new Fy(r):new DOMException(r),CA=r=>{let e=r.reason===void 0?DA("This operation was aborted."):r.reason;return e instanceof Error?e:DA(e)};function Ky(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(CA(h)),h.addEventListener("abort",()=>{l(CA(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new Iu;o=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},c}var OG=r=>{let e=r.on||r.addListener||r.addEventListener,t=r.off||r.removeListener||r.removeEventListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function BG(r,e,t){let n,i=new Promise((s,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=OG(r),f=(...d)=>{let p=t.multiArgs?d:d[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},h=d=>{n(),o(d)};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)l(d,h)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)u(d,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(i.cancel=n,typeof t.timeout=="number"){let s=Ky(i,{milliseconds:t.timeout});return s.cancel=n,s}return i}function PA(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=BG(r,e,t),i=n.then(s=>s[0]);return i.cancel=n.cancel,i}var Jn;(function(r){let e;(function(i){i.FIN="FIN",i.STOP_SENDING="STOP_SENDING",i.RESET="RESET"})(e=r.Flag||(r.Flag={}));let t;(function(i){i[i.FIN=0]="FIN",i[i.STOP_SENDING=1]="STOP_SENDING",i[i.RESET=2]="RESET"})(t||(t={})),function(i){i.codec=()=>ft(t)}(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.flag!=null&&(s.uint32(8),r.Flag.codec().encode(i.flag,s)),i.message!=null&&(s.uint32(18),s.bytes(i.message)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.flag=r.Flag.codec().decode(i);break;case 2:o.message=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(Jn||(Jn={}));var Yf=C("libp2p:webrtc:stream"),kA=16*1024,LG=16*1024*1024,MG=30*1e3,UG=3,Vy=class extends Io{channel;dataChannelOptions;incomingData;messageQueue;maxDataSize;constructor(e){switch(super(e),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=Pt(),this.messageQueue=new Te,this.dataChannelOptions={bufferedAmountLowEventTimeout:e.dataChannelOptions?.bufferedAmountLowEventTimeout??MG,maxBufferedAmount:e.dataChannelOptions?.maxBufferedAmount??LG,maxMessageSize:e.dataChannelOptions?.maxMessageSize??kA},this.maxDataSize=e.maxDataSize,this.channel.readyState){case"open":break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw Yf.error("unknown datachannel state %s",this.channel.readyState),new w("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=n=>{this.timeline.open=new Date().getTime(),this.messageQueue!=null&&(this._sendMessage(this.messageQueue).catch(i=>{this.abort(i)}),this.messageQueue=void 0)},this.channel.onclose=n=>{this.close().catch(i=>{Yf.error("error closing stream after channel closed",i)})},this.channel.onerror=n=>{let i=n.error;this.abort(i)};let t=this;this.channel.onmessage=async n=>{let{data:i}=n;i===null||i.byteLength===0||this.incomingData.push(new Uint8Array(i,0,i.byteLength))},Promise.resolve().then(async()=>{for await(let n of Yt(this.incomingData)){let i=t.processIncomingProtobuf(n.subarray());i!=null&&t.sourcePush(new Te(i))}}).catch(n=>{Yf.error("error processing incoming data channel messages",n)})}sendNewStream(){}async _sendMessage(e,t=!0){if(t&&this.channel.bufferedAmount>this.dataChannelOptions.maxBufferedAmount)try{await PA(this.channel,"bufferedamountlow",{timeout:this.dataChannelOptions.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Iu?new Error("Timed out waiting for DataChannel buffer to clear"):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new w("Invalid datachannel state - closed or closing","ERR_INVALID_STATE");if(this.channel.readyState==="open")for(let n of e)this.channel.send(n);else if(this.channel.readyState==="connecting")this.messageQueue==null&&(this.messageQueue=new Te),this.messageQueue.append(e);else throw Yf.error("unknown datachannel state %s",this.channel.readyState),new w("Unknown datachannel state","ERR_INVALID_STATE")}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize),n=e.subarray(0,t),i=Jn.encode({message:n}),s=Kt.single(i);await this._sendMessage(s),e.consume(t)}}async sendReset(){await this._sendFlag(Jn.Flag.RESET)}async sendCloseWrite(){await this._sendFlag(Jn.Flag.FIN)}async sendCloseRead(){await this._sendFlag(Jn.Flag.STOP_SENDING)}processIncomingProtobuf(e){let t=Jn.decode(e);return t.flag!==void 0&&(t.flag===Jn.Flag.FIN&&(this.incomingData.end(),this.remoteCloseWrite()),t.flag===Jn.Flag.RESET&&this.reset(),t.flag===Jn.Flag.STOP_SENDING&&this.remoteCloseRead()),t.message}async _sendFlag(e){Yf.trace("Sending flag: %s",e.toString());let t=Jn.encode({flag:e}),n=Kt.single(t);await this._sendMessage(n,!1)}};function Au(r){let{channel:e,direction:t,onEnd:n,dataChannelOptions:i}=r;return new Vy({id:t==="inbound"?`i${e.id}`:`r${e.id}`,direction:t,maxDataSize:(i?.maxMessageSize??kA)-UG,dataChannelOptions:i,onEnd:n,channel:e,log:C(`libp2p:mplex:stream:${t}:${e.id}`)})}var NA="/webrtc",Wa=class{protocol;peerConnection;streamBuffer=[];metrics;dataChannelOptions;constructor(e){this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??NA,this.dataChannelOptions=e.dataChannelOptions,this.peerConnection.ondatachannel=({channel:t})=>{let n=Au({channel:t,direction:"inbound",dataChannelOptions:e.dataChannelOptions,onEnd:()=>{this.streamBuffer=this.streamBuffer.filter(i=>i.id!==n.id)}});this.streamBuffer.push(n)}}createStreamMuxer(e){return new qy({...e,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.streamBuffer,protocol:this.protocol})}},qy=class{init;streams;protocol;peerConnection;dataChannelOptions;metrics;close=async()=>{};abort=()=>{};source=yp();sink=bp;constructor(e){this.init=e,this.streams=e.streams,this.peerConnection=e.peerConnection,this.protocol=e.protocol??NA,this.metrics=e.metrics,this.peerConnection.ondatachannel=({channel:n})=>{let i=Au({channel:n,direction:"inbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{this.streams=this.streams.filter(s=>s.id!==i.id),this.metrics?.increment({stream_end:!0}),e?.onStreamEnd?.(i)}});this.streams.push(i),e?.onIncomingStream!=null&&(this.metrics?.increment({incoming_stream:!0}),e.onIncomingStream(i))};let t=e?.onIncomingStream;t!=null&&this.streams.forEach(n=>{t(n)})}newStream(){let e=this.peerConnection.createDataChannel(""),t=Au({channel:e,direction:"outbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}});return this.streams.push(t),this.metrics?.increment({outgoing_stream:!0}),t}};var _n;(function(r){let e;(function(i){i.SDP_OFFER="SDP_OFFER",i.SDP_ANSWER="SDP_ANSWER",i.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.SDP_OFFER=0]="SDP_OFFER",i[i.SDP_ANSWER=1]="SDP_ANSWER",i[i.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(i){i.codec=()=>ft(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.data!=null&&(s.uint32(18),s.string(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.data=i.string();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(_n||(_n={}));var wp=C("libp2p:webrtc:peer:util"),zy=async(r,e,t)=>{for(;;){let n=await Promise.race([r.promise,t.read()]);if(n instanceof Object){let i=n;if(i.type!==_n.Type.ICE_CANDIDATE)throw new Error("expected only ice candidates");if(i.data==null||i.data===""){wp.trace("end-of-candidates received");break}wp.trace("received new ICE candidate: %s",i.data);try{await e.addIceCandidate(new TA(JSON.parse(i.data)))}catch(s){throw wp.error("bad candidate received: ",s),new Error("bad candidate received")}}else break}await r.promise};function $y(r,e){r[Wf?"oniceconnectionstatechange":"onconnectionstatechange"]=t=>{switch(wp.trace("receiver peerConnectionState state: ",r.connectionState),Wf?r.iceConnectionState:r.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new Error("RTCPeerConnection was closed"));break;default:break}}}var FG=30*1e3,ko=C("libp2p:webrtc:peer");async function OA({rtcConfiguration:r,dataChannelOptions:e,stream:t}){let n=AbortSignal.timeout(FG),i=_r(Ri(t,n)).pb(_n),s=new Ru(r);try{let o=new Wa({peerConnection:s,dataChannelOptions:e}),a=Le(),c=Le();n.onabort=()=>{a.reject(new w("Timed out while trying to connect","ERR_TIMEOUT"))},s.onicecandidate=({candidate:d})=>{c.promise.then(async()=>{await i.write({type:_n.Type.ICE_CANDIDATE,data:d!=null?JSON.stringify(d.toJSON()):""})},p=>{ko.error("cannot set candidate since sending answer failed",p),a.reject(p)})},$y(s,a);let u=await i.read();if(u.type!==_n.Type.SDP_OFFER)throw new Error(`expected message type SDP_OFFER, received: ${u.type??"undefined"} `);let l=new Uy({type:"offer",sdp:u.data});await s.setRemoteDescription(l).catch(d=>{throw ko.error("could not execute setRemoteDescription",d),new Error("Failed to set remoteDescription")});let f=await s.createAnswer().catch(d=>{throw ko.error("could not execute createAnswer",d),c.reject(d),new Error("Failed to create answer")});await i.write({type:_n.Type.SDP_ANSWER,data:f.sdp}),await s.setLocalDescription(f).catch(d=>{throw ko.error("could not execute setLocalDescription",d),c.reject(d),new Error("Failed to set localDescription")}),c.resolve(),await zy(a,s,i);let h=LA(s.currentRemoteDescription?.sdp??"");return{pc:s,muxerFactory:o,remoteAddress:h}}catch(o){throw s.close(),o}}async function BA({rtcConfiguration:r,dataChannelOptions:e,signal:t,stream:n}){let i=_r(Ri(n,t)).pb(_n),s=new Ru(r);try{let o=new Wa({peerConnection:s,dataChannelOptions:e}),a=Le();$y(s,a),t.onabort=a.reject;let c=s.createDataChannel("init");s.onicecandidate=({candidate:d})=>{i.write({type:_n.Type.ICE_CANDIDATE,data:d!=null?JSON.stringify(d.toJSON()):""}).catch(p=>{ko.error("error sending ICE candidate",p)})};let u=await s.createOffer();await i.write({type:_n.Type.SDP_OFFER,data:u.sdp}),await s.setLocalDescription(u).catch(d=>{throw ko.error("could not execute setLocalDescription",d),new Error("Failed to set localDescription")});let l=await i.read();if(l.type!==_n.Type.SDP_ANSWER)throw new Error("remote should send an SDP answer");let f=new Uy({type:"answer",sdp:l.data});await s.setRemoteDescription(f).catch(d=>{throw ko.error("could not execute setRemoteDescription",d),new Error("Failed to set remoteDescription")}),await zy(a,s,i),c.close();let h=LA(s.currentRemoteDescription?.sdp??"");return{pc:s,muxerFactory:o,remoteAddress:h}}catch(o){throw s.close(),o}}function LA(r){let e=r.split(`\r `).filter(n=>n.startsWith("a=candidate")).pop(),t=e?.split(" ");return e==null||t==null||t.length<5?(ko("could not parse remote address from",e),"/webrtc"):`/dnsaddr/${t[4]}/${t[2].toLowerCase()}/${t[3]}/webrtc`}var Ep=class extends Ye{peerId;transportManager;constructor(e){super(),this.peerId=e.peerId,this.transportManager=e.transportManager}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(e=>e!==this).map(e=>e.getAddrs().filter(t=>Ai.matches(t)).map(t=>t.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.safeDispatchEvent("close",{})}};var MA=C("libp2p:webrtc:peer"),KG="/webrtc",VG="/p2p-circuit",Hy="/webrtc-signaling/0.0.1",qG=le("webrtc").code,xp=class{components;init;_started=!1;constructor(e,t={}){this.components=e,this.init=t}isStarted(){return this._started}async start(){await this.components.registrar.handle(Hy,e=>{this._onProtocol(e).catch(t=>{MA.error("failed to handle incoming connect from %p",e.connection.remotePeer,t)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Hy),this._started=!1}createListener(e){return new Ep(this.components)}[Symbol.toStringTag]="@libp2p/webrtc";[Ji]=!0;filter(e){return e.filter(t=>t.protoCodes().includes(qG))}async dial(e,t){MA.trace("dialing address: ",e);let{baseAddr:n,peerId:i}=zG(e);if(t.signal==null){let a=new AbortController;t.signal=a.signal}let s=await this.components.transportManager.dial(n,t),o=await s.newStream(Hy,{...t,runOnTransientConnection:!0});try{let{pc:a,muxerFactory:c,remoteAddress:u}=await BA({stream:o,rtcConfiguration:this.init.rtcConfiguration,dataChannelOptions:this.init.dataChannel,signal:t.signal}),l=await t.upgrader.upgradeOutbound(new Ga({peerConnection:a,timeline:{open:Date.now()},remoteAddr:ge(u).encapsulate(`/p2p/${i.toString()}`)}),{skipProtection:!0,skipEncryption:!0,muxerFactory:c});return await o.close(),l}catch(a){throw o.abort(a),a}finally{await s.close()}}async _onProtocol({connection:e,stream:t}){try{let{pc:n,muxerFactory:i,remoteAddress:s}=await OA({rtcConfiguration:this.init.rtcConfiguration,connection:e,stream:t,dataChannelOptions:this.init.dataChannel});await this.components.upgrader.upgradeInbound(new Ga({peerConnection:n,timeline:{open:new Date().getTime()},remoteAddr:ge(s).encapsulate(`/p2p/${e.remotePeer.toString()}`)}),{skipEncryption:!0,skipProtection:!0,muxerFactory:i})}catch(n){throw t.abort(n),n}finally{await e.close()}}};function zG(r){let e=r.toString().split(KG+"/");if(e.length!==2)throw new w("webrtc protocol was not present in multiaddr",vn.ERR_INVALID_MULTIADDR);if(!e[0].includes(VG))throw new w("p2p-circuit protocol was not present in multiaddr",vn.ERR_INVALID_MULTIADDR);let t=ge(e[0]),i=ge("/"+e[1]).getPeerId();if(i==null)throw new w("destination peer id was missing",vn.ERR_INVALID_MULTIADDR);let s=t.protos().pop();if(s===void 0)throw new w("invalid multiaddr",vn.ERR_INVALID_MULTIADDR);return s.name!=="p2p"&&(t=t.encapsulate(`/p2p/${i}`)),{baseAddr:t,peerId:we(i)}}var hD=j(x8(),1);var oD=j(x8(),1);var v8=C("libp2p:webrtc:sdp"),_8=Object.values(Bn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function aD(r){let e=r.getConfiguration().certificates?.at(0);if(e==null||e.getFingerprints==null){v8.trace("fetching fingerprint from local SDP");let n=r.localDescription;return n==null?void 0:XY(n.sdp)}if(v8.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let t=e.getFingerprints()[0].value;if(t==null)throw My("","no fingerprint on local certificate");return t}var QY=/^a=fingerprint:(?:\w+-[0-9]+)\s(?(:?[0-9a-fA-F]{2})+)$/m;function XY(r){return r.match(QY)?.groups?.fingerprint}function jY(r){for(let e of r.protoNames())if(e.startsWith("ip"))return e.toUpperCase();return v8("Warning: multiaddr does not appear to contain IP4 or IP6, defaulting to IP6",r),"IP6"}function Np(r){let t=r.stringTuples().filter(n=>n[0]===I8).map(n=>n[1])[0];if(t===void 0||t==="")throw gp(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function S8(r){let e=_8.decode(r);return oD.decode(e)}function ZY(r){let e=S8(Np(r)),t=R8(e.name),n=e.digest.reduce((s,o)=>s+o.toString(16).padStart(2,"0"),""),i=n.match(/.{1,2}/g);if(i==null)throw My(n,r.toString());return[`${t.toUpperCase()} ${i.join(":").toUpperCase()}`,n]}function R8(r){switch(r){case"sha1":return"sha-1";case"sha2-256":return"sha-256";case"sha2-512":return"sha-512";default:throw EA(r)}}function JY(r,e){let{host:t,port:n}=r.toOptions(),i=jY(r),[s]=ZY(r);return`v=0 o=- 0 0 IN ${i} ${t} s=- c=IN ${i} ${t} t=0 0 a=ice-lite m=application ${n} UDP/DTLS/SCTP webrtc-datachannel a=mid:0 a=setup:passive a=ice-ufrag:${e} a=ice-pwd:${e} a=fingerprint:${s} a=sctp-port:5000 a=max-message-size:16384 a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r `}function cD(r,e){return{type:"answer",sdp:JY(r,e)}}function uD(r,e){if(r.sdp===void 0)throw Gf("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,` a=ice-ufrag:`+e+` `).replace(/\na=ice-pwd:[^\n]*\n/,` a=ice-pwd:`+e+` `),r}var lD=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),fD=r=>[...Array(r)].map(()=>lD.at(Math.floor(Math.random()*lD.length))).join("");var Op=C("libp2p:webrtc:transport"),tQ=1e4,rQ=le("webrtc-direct").code,I8=le("certhash").code,Bp=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return Op(`dialing address - ${e.toString()}`),n}createListener(e){throw wA("WebRTCTransport.createListener")}filter(e){return e.filter(nQ)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ji]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw gp("we need to have the remote's PeerId");let o=we(s),a=S8(Np(e)),c=await Ru.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:R8(a.name)}),u=new Ru({certificates:[c]});try{let l=new Promise((T,P)=>{let q=u.createDataChannel("",{negotiated:!0,id:0}),$=setTimeout(()=>{let Q=`Data channel was never opened: state: ${q.readyState}`;Op.error(Q),this.metrics?.dialerEvents.increment({open_error:!0}),P(Ly("data",Q))},tQ);q.onopen=Q=>{clearTimeout($),T(q)},q.onerror=Q=>{clearTimeout($);let _e=`Error opening a data channel for handshaking: ${Q.target?.toString()??"not specified"}`;Op.error(_e),this.metrics?.dialerEvents.increment({unknown_error:!0}),P(Ly("data",_e))}}),f="libp2p+webrtc+v1/"+fD(32),h=await u.createOffer(),d=uD(h,f);await u.setLocalDescription(d);let p=cD(e,f);await u.setRemoteDescription(p);let m=await l,g=this.components.peerId,y=this.generateNoisePrologue(u,a.code,e),b=mu({prologueBytes:y})(),E=Au({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),_={...E,sink:E.sink.bind(E),source:async function*(){for await(let T of E.source)for(let P of T)yield P}()},x=new Ga({peerConnection:u,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),v=Wf?"iceconnectionstatechange":"connectionstatechange";u.addEventListener(v,()=>{switch(u.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(T=>{Op.error("error closing connection",T)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let R=new Wa({peerConnection:u,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,_,o),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:R})}catch(l){throw u.close(),l}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Gf("no local certificate");let i=aD(e);if(i==null)throw Gf("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=G(s,"hex"),a=hD.encode(o,t),c=_8.decode(Np(n)),u=G("libp2p-webrtc-noise:");return ve([u,a,c])}};function nQ(r){let e=r.protoCodes();return e.includes(rQ)&&e.includes(I8)&&r.getPeerId()!=null&&!e.includes(le("p2p-circuit").code)}function dD(r){return e=>new Bp(e,r)}function pD(r){return e=>new xp(e,r)}function mD(r){let e;try{e=le("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function gD(r){return r.some(([e,t])=>e===le("tls").code)}function Sn(r,e,t){let n=yD[le(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${le(r).name}`);let i=n(e,t);return r===le("ip6").code?`[${i}]`:i}var yD={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${Sn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${Sn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Sn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Sn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=gD(e),n=mD(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=Sn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return Sn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return Sn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=Sn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=gD(e),n=mD(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=Sn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=Sn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Sn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Sn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${Sn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function bD(r,e){let n=ge(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=le(i[0]),o=yD[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===le("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var wD=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var ED=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await wD(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var SD=j(vD(),1);function _D(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var RD=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=l=>{r.removeEventListener("open",c),r.removeEventListener("error",u),l()},c=()=>{a(s)},u=l=>{a(()=>{o(l.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",u)})},t=async function*(){let s=new SD.EventIterator(({push:o,stop:a,fail:c})=>{let u=f=>{let h=null;typeof f.data=="string"&&(h=G(f.data)),_D(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&o(h)},l=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",u),r.addEventListener("error",l),r.addEventListener("close",a),()=>{r.removeEventListener("message",u),r.removeEventListener("error",l),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of s)yield _D(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var ID=(r,e)=>{e=e??{};let t=RD(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:ED(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var AD=WebSocket;var BD=j(OD(),1),pQ={http:"ws",https:"wss"},mQ="ws",LD=(r,e)=>(0,BD.relative)(r,e,pQ,mQ);function MD(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=LD(r,t.toString()),i=new AD(n,e.websocket);return ID(i,e)}var KD=j(FD(),1),P8=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Up=(0,KD.default)(),Fp=P8&&!Up,VD=Up&&!P8,qD=Up&&P8,zD=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Up,Kp=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,fxe=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",$D=typeof navigator<"u"&&navigator.product==="ReactNative";function WD(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return bu.matches(t)||qa.matches(t)})}function YD(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return qa.matches(t)})}function QD(){throw new Error("WebSocket Servers can not be created in the browser!")}var k8=C("libp2p:websockets:socket");function XD(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=Er(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&k8.error(s)}},source:t.signal!=null?Er(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(i={}){let s=Date.now();i.signal=i.signal??AbortSignal.timeout(500);let o=()=>{let{host:a,port:c}=n.remoteAddr.toOptions();k8("timeout closing stream to %s:%s after %dms, destroying it manually",a,c,Date.now()-s),this.abort(new w("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};i.signal.addEventListener("abort",o);try{await r.close()}catch(a){this.abort(a)}finally{i.signal.removeEventListener("abort",o),n.timeline.close=Date.now()}},abort(i){let{host:s,port:o}=n.remoteAddr.toOptions();k8("timeout closing stream to %s:%s due to error",s,o,i),r.destroy(),n.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var Bo=C("libp2p:websockets"),N8=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[Ji]=!0;async dial(e,t){Bo("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=XD(n,e);Bo("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return Bo("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new ai;let n=e.toOptions();Bo("dialing %s:%s",n.host,n.port);let i=Le(),s=MD(bD(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new w(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");Bo.error("connection error:",c),i.reject(c)}),t.signal==null)return await Promise.race([s.connected(),i.promise]),Bo("connected %s",e),s;let o,a=new Promise((c,u)=>{if(o=()=>{u(new ai),s.close().catch(l=>{Bo.error("error closing raw socket",l)})},t?.signal?.aborted===!0){o();return}t?.signal?.addEventListener("abort",o)});try{await Promise.race([a,i.promise,s.connected()])}finally{o!=null&&t?.signal?.removeEventListener("abort",o)}return Bo("connected %s",e),s}createListener(e){return QD({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Fp||Kp?YD(e):WD(e)}};function jD(r={}){return()=>new N8(r)}var Vp=C("libp2p:webtransport:stream");async function O8(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let h=n.findIndex(d=>d===f);h!==-1&&(n.splice(h,1),f.timeline.close=Date.now(),i?.(f))}let c=!1,u=!1;(async function(){let h=await s.closed.catch(d=>d);if(h!=null){let d=h.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||Vp.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${h.message}`)}c=!0,c&&u&&a()})().catch(()=>{Vp.error("WebTransport failed to cleanup closed stream")}),async function(){let h=await o.closed.catch(d=>d);h!=null&&Vp.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${h.message}`),u=!0,c&&u&&a()}().catch(()=>{Vp.error("WebTransport failed to cleanup closed stream")});let l=!1,f={id:e,status:"open",writeStatus:"ready",readStatus:"ready",abort(h){c||(s.abort(h),c=!0),u=!0,this.status="aborted",this.writeStatus="closed",this.readStatus="closed",this.timeline.reset=this.timeline.close=this.timeline.closeRead=this.timeline.closeWrite=Date.now(),a()},async close(h){this.status="closing",await Promise.all([f.closeRead(h),f.closeWrite(h)]),a(),this.status="closed",this.timeline.close=Date.now()},async closeRead(h){if(!u){this.readStatus="closing";try{await o.cancel()}catch(d){d.toString().includes("RESET_STREAM")===!0&&(c=!0)}this.timeline.closeRead=Date.now(),this.readStatus="closed",u=!0}c&&a()},async closeWrite(h){if(!c){c=!0,this.writeStatus="closing";try{await s.close()}catch(d){d.toString().includes("RESET_STREAM")===!0&&(u=!0)}this.timeline.closeWrite=Date.now(),this.writeStatus="closed"}u&&a()},direction:t,timeline:{open:Date.now()},metadata:{},source:async function*(){for(;;){let h=await o.read();if(h.done===!0){u=!0,c&&a();return}yield new Te(h.value)}}(),sink:async function(h){if(l)throw new Error("sink already called on stream");l=!0;try{this.writeStatus="writing";for await(let d of h)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p);this.writeStatus="done"}finally{this.timeline.closeWrite=Date.now(),this.writeStatus="closed",await f.closeWrite()}}};return f}function B8(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function ZD(r,e){return e.filter(n=>!!r.find(i=>fe(n,i))).length===e.length}var wQ=Object.values(Bn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function EQ(r){return si.decode(wQ.decode(r))}function JD(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case le("ip6").code:case le("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case le("ip4").code:case le("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case le("quic").code:case le("quic-v1").code:case le("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case le("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case le("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([EQ(a??"")])};case le("p2p").code:return{...s,remotePeer:we(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${le(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}var Rn=C("libp2p:webtransport"),L8=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[Ji]=!0;async dial(e,t){t?.signal?.throwIfAborted(),Rn("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=JD(e);if(o==null)throw new Error("Need a target peerid");if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a,c,u=()=>{};try{let l=!1,f=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(h=>({algorithm:"sha-256",value:h.digest}))});if(u=h=>{try{if(c!=null){if(c.timeline.close!=null)return;c.timeline.close=Date.now()}if(l)return;f.close(h)}catch(d){Rn.error("error closing wt session",d)}finally{l=!0}},f.closed.then(async()=>{await c?.close()}).catch(h=>{Rn.error("error on remote wt session close",h),c?.abort(h)}).finally(()=>{c==null&&u()}),a=()=>{a!=null&&t.signal?.removeEventListener("abort",a),u()},t.signal?.addEventListener("abort",a),await f.ready,!await this.authenticateWebTransport(f,n,o,s))throw new Error("Failed to authenticate webtransport");return c={close:async h=>{Rn("Closing webtransport"),u()},abort:h=>{Rn("aborting webtransport due to passed err",h),u({closeCode:0,reason:h.message})},remoteAddr:e,timeline:{open:Date.now()},...B8()},t?.signal?.throwIfAborted(),await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(f,u),skipProtection:!0})}catch(l){throw Rn.error("caught wt session err",l),u({closeCode:0,reason:l.message}),l}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let f=await a.read();if(f.value!=null&&(yield f.value),f.done===!0)break}}(),sink:async function(f){for await(let h of f)await o.write(h)}},u=mu()(),{remoteExtensions:l}=await u.secureOutbound(t,c,n);if(o.close().catch(f=>{Rn.error(`Failed to close authentication stream writer: ${f.message}`)}),a.cancel().catch(f=>{Rn.error(`Failed to close authentication stream reader: ${f.message}`)}),!ZD(l?.webtransportCerthashes??[],i.map(f=>f.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e,t){let n=0,i=this.config;return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let o=[];return async function(){let c=e.incomingBidirectionalStreams.getReader();for(;;){let{done:u,value:l}=await c.read();if(u===!0)break;if(o.length>=i.maxInboundStreams)l.writable.close().catch(f=>{Rn.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${f.message}`)}),l.readable.cancel().catch(f=>{Rn.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${f.message}`)});else{let f=await O8(l,String(n++),"inbound",o,s?.onStreamEnd);o.push(f),s?.onIncomingStream?.(f)}}}().catch(()=>{Rn.error("WebTransport failed to receive incoming stream")}),{protocol:"webtransport",streams:o,newStream:async c=>{let u=await e.createBidirectionalStream(),l=await O8(u,String(n++),s?.direction??"outbound",o,s?.onStreamEnd);return o.push(l),l},close:async c=>{Rn("Closing webtransport muxer"),t()},abort:c=>{Rn("Aborting webtransport muxer with err:",c),t({closeCode:0,reason:c.message})},...B8()}}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function eC(r={}){return e=>new L8(e,r)}var ns;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>ft(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.value!=null&&(s.uint32(10),s.bytes(i.value)),i.signature!=null&&(s.uint32(18),s.bytes(i.signature)),i.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(i.validityType,s)),i.validity!=null&&(s.uint32(34),s.bytes(i.validity)),i.sequence!=null&&(s.uint32(40),s.uint64(i.sequence)),i.ttl!=null&&(s.uint32(48),s.uint64(i.ttl)),i.pubKey!=null&&(s.uint32(58),s.bytes(i.pubKey)),i.signatureV2!=null&&(s.uint32(66),s.bytes(i.signatureV2)),i.data!=null&&(s.uint32(74),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.value=i.bytes();break;case 2:o.signature=i.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(i);break;case 4:o.validity=i.bytes();break;case 5:o.sequence=i.uint64();break;case 6:o.ttl=i.uint64();break;case 7:o.pubKey=i.bytes();break;case 8:o.signatureV2=i.bytes();break;case 9:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(ns||(ns={}));var L_e=j(ma(),1),M_e=j(M3(),1);var ut=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var XX=j(Ve(),1);var s5={};be(s5,{Ed25519PrivateKey:()=>ja,Ed25519PublicKey:()=>hh,generateKeyPair:()=>yX,generateKeyPairFromSeed:()=>CC,unmarshalEd25519PrivateKey:()=>mX,unmarshalEd25519PublicKey:()=>gX});var V8={};be(V8,{base58btc:()=>Rr,base58flickr:()=>IQ});function xQ(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,_=new Uint8Array(E);y!==b;){for(var x=p[y],v=0,R=E-1;(x!==0||v>>0,_[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");g=v,y++}for(var T=E-g;T!==E&&_[T]===0;)T++;for(var P=c.repeat(m);T>>0,E=new Uint8Array(b);p[m];){var _=t[p.charCodeAt(m)];if(_===255)return;for(var x=0,v=b-1;(_!==0||x>>0,E[v]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=x,m++}if(p[m]!==" "){for(var R=b-y;R!==b&&E[R]===0;)R++;for(var T=new Uint8Array(g+(b-R)),P=g;R!==b;)T[P++]=E[R++];return T}}}function d(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var vQ=xQ,_Q=vQ,tC=_Q;var nve=new Uint8Array(0);var rC=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")};var nC=r=>new TextEncoder().encode(r),iC=r=>new TextDecoder().decode(r);var M8=class{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},U8=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return oC(this,e)}},F8=class{constructor(e){this.decoders=e}or(e){return oC(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},oC=(r,e)=>new F8({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),K8=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new M8(e,t,n),this.decoder=new U8(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Mu=({name:r,prefix:e,encode:t,decode:n})=>new K8(r,e,t,n),Lo=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=tC(t,e);return Mu({prefix:r,name:e,encode:n,decode:s=>Vs(i(s))})},SQ=(r,e,t,n)=>{let i={};for(let l=0;l=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},RQ=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<Mu({prefix:e,name:r,encode(i){return RQ(i,n,t)},decode(i){return SQ(i,n,t,r)}});var Rr=Lo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),IQ=Lo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var z8={};be(z8,{identity:()=>Mo});var AQ=uC,aC=128,TQ=127,DQ=~TQ,CQ=Math.pow(2,31);function uC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=CQ;)e[t++]=r&255|aC,r/=128;for(;r&DQ;)e[t++]=r&255|aC,r>>>=7;return e[t]=r|0,uC.bytes=t-n+1,e}var PQ=q8,kQ=128,cC=127;function q8(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw q8.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&cC)<=kQ);return q8.bytes=s-n,t}var NQ=Math.pow(2,7),OQ=Math.pow(2,14),BQ=Math.pow(2,21),LQ=Math.pow(2,28),MQ=Math.pow(2,35),UQ=Math.pow(2,42),FQ=Math.pow(2,49),KQ=Math.pow(2,56),VQ=Math.pow(2,63),qQ=function(r){return r[ih.decode(r,e),ih.decode.bytes],Uu=(r,e,t=0)=>(ih.encode(r,e,t),e),Fu=r=>ih.encodingLength(r);var is=(r,e)=>{let t=e.byteLength,n=Fu(r),i=n+Fu(t),s=new Uint8Array(i+t);return Uu(r,s,0),Uu(t,s,n),s.set(e,i),new Ku(r,t,e,s)},oh=r=>{let e=Vs(r),[t,n]=sh(e),[i,s]=sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Ku(t,i,o,e)},lC=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&rC(r.bytes,t.bytes)}},Ku=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var fC=0,HQ="identity",hC=Vs,GQ=r=>is(fC,hC(r)),Mo={code:fC,name:HQ,encode:hC,digest:GQ};var G8={};be(G8,{sha256:()=>Ir,sha512:()=>WQ});var H8=({name:r,code:e,encode:t})=>new $8(r,e,t),$8=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?is(this.code,t):t.then(n=>is(this.code,n))}else throw Error("Unknown type, must be binary type")}};var pC=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ir=H8({name:"sha2-256",code:18,encode:pC("SHA-256")}),WQ=H8({name:"sha2-512",code:19,encode:pC("SHA-512")});var YQ=j(ba(),1);var fr=BigInt(0),$e=BigInt(1),Ko=BigInt(2),QQ=BigInt(8),mC=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),Et=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:mC,n:mC,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var EC=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),ah=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),dve=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),XQ=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),jQ=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ZQ=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),JQ=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),rr=class r{constructor(e,t,n,i){this.x=e,this.y=t,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof Ht))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(Ht.ZERO)?r.ZERO:new r(e.x,e.y,$e,V(e.x*e.y))}static toAffineBatch(e){let t=rX(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){yC(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=V(t*a),u=V(s*i),l=V(n*a),f=V(o*i);return c===u&&l===f}negate(){return new r(V(-this.x),this.y,this.z,V(-this.t))}double(){let{x:e,y:t,z:n}=this,{a:i}=Et,s=V(e*e),o=V(t*t),a=V(Ko*V(n*n)),c=V(i*s),u=e+t,l=V(V(u*u)-s-o),f=c+o,h=f-a,d=c-o,p=V(l*h),m=V(f*d),g=V(l*d),y=V(h*f);return new r(p,m,y,g)}add(e){yC(e);let{x:t,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:u}=e,l=V((n-t)*(a+o)),f=V((n+t)*(a-o)),h=V(f-l);if(h===fr)return this.double();let d=V(i*Ko*u),p=V(s*Ko*c),m=p+d,g=f+l,y=p-d,b=V(m*h),E=V(g*y),_=V(m*y),x=V(h*g);return new r(b,E,x,_)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let t=1+256/e,n=[],i=this,s=i;for(let o=0;o>=f,p>c&&(p-=l,e+=$e);let m=d,g=d+Math.abs(p)-1,y=h%2!==0,b=p<0;p===0?o=o.add(gC(y,i[m])):s=s.add(gC(b,i[g]))}return r.normalizeZ([s,o])[0]}multiply(e,t){return this.wNAF($p(e,Et.l),t)}multiplyUnsafe(e){let t=$p(e,Et.l,!1),n=r.BASE,i=r.ZERO;if(t===fr)return i;if(this.equals(i)||t===$e)return this;if(this.equals(n))return this.wNAF(t);let s=i,o=this;for(;t>fr;)t&$e&&(s=s.add(o)),o=o.double(),t>>=$e;return s}isSmallOrder(){return this.multiplyUnsafe(Et.h).equals(r.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(Et.l/Ko).double();return Et.l%Ko&&(e=e.add(this)),e.equals(r.ZERO)}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(r.ZERO);e==null&&(e=s?QQ:Hp(i));let o=V(t*e),a=V(n*e),c=V(i*e);if(s)return Ht.ZERO;if(c!==$e)throw new Error("invZ was invalid");return new Ht(o,a)}fromRistrettoBytes(){Y8()}toRistrettoBytes(){Y8()}fromRistrettoHash(){Y8()}};rr.BASE=new rr(Et.Gx,Et.Gy,$e,V(Et.Gx*Et.Gy));rr.ZERO=new rr(fr,$e,$e,fr);function gC(r,e){let t=e.negate();return r?t:e}function yC(r){if(!(r instanceof rr))throw new TypeError("ExtendedPoint expected")}function W8(r){if(!(r instanceof Xa))throw new TypeError("RistrettoPoint expected")}function Y8(){throw new Error("Legacy method: switch to RistrettoPoint")}var Xa=class r{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:t}=Et,n=V(ah*e*e),i=V((n+$e)*ZQ),s=BigInt(-1),o=V((s-t*n)*V(n+t)),{isValid:a,value:c}=J8(i,o),u=V(c*e);Fo(u)||(u=V(-u)),a||(c=u),a||(s=n);let l=V(s*(n-$e)*JQ-o),f=c*c,h=V((c+c)*o),d=V(l*XQ),p=V($e-f),m=V($e+f);return new rr(V(h*m),V(p*d),V(d*m),V(h*p))}static hashToCurve(e){e=Vo(e,64);let t=Q8(e.slice(0,32)),n=this.calcElligatorRistrettoMap(t),i=Q8(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new r(n.add(s))}static fromHex(e){e=Vo(e,32);let{a:t,d:n}=Et,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=Q8(e);if(!iX(uh(s),e)||Fo(s))throw new Error(i);let o=V(s*s),a=V($e+t*o),c=V($e-t*o),u=V(a*a),l=V(c*c),f=V(t*n*u-l),{isValid:h,value:d}=wC(V(f*l)),p=V(d*c),m=V(d*p*f),g=V((s+s)*p);Fo(g)&&(g=V(-g));let y=V(a*m),b=V(g*y);if(!h||Fo(b)||y===fr)throw new Error(i);return new r(new rr(g,y,$e,b))}toRawBytes(){let{x:e,y:t,z:n,t:i}=this.ep,s=V(V(n+t)*V(n-t)),o=V(e*t),a=V(o*o),{value:c}=wC(V(s*a)),u=V(c*s),l=V(c*o),f=V(u*l*i),h;if(Fo(i*f)){let p=V(t*ah),m=V(e*ah);e=p,t=m,h=V(u*jQ)}else h=l;Fo(e*f)&&(t=V(-t));let d=V((n-t)*h);return Fo(d)&&(d=V(-d)),uh(d)}toHex(){return lh(this.toRawBytes())}toString(){return this.toHex()}equals(e){W8(e);let t=this.ep,n=e.ep,i=V(t.x*n.y)===V(t.y*n.x),s=V(t.y*n.y)===V(t.x*n.x);return i||s}add(e){return W8(e),new r(this.ep.add(e.ep))}subtract(e){return W8(e),new r(this.ep.subtract(e.ep))}multiply(e){return new r(this.ep.multiply(e))}multiplyUnsafe(e){return new r(this.ep.multiplyUnsafe(e))}};Xa.BASE=new Xa(rr.BASE);Xa.ZERO=new Xa(rr.ZERO);var j8=new WeakMap,Ht=class r{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,j8.delete(this)}static fromHex(e,t=!0){let{d:n,P:i}=Et;e=Vo(e,32);let s=e.slice();s[31]=e[31]&-129;let o=fh(s);if(t&&o>=i)throw new Error("Expected 0 < hex < P");if(!t&&o>=EC)throw new Error("Expected 0 < hex < 2**256");let a=V(o*o),c=V(a-$e),u=V(n*a+$e),{isValid:l,value:f}=J8(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let h=(f&$e)===$e;return(e[31]&128)!==0!==h&&(f=V(-f)),new r(f,o)}static async fromPrivateKey(e){return(await Gp(e)).point}toRawBytes(){let e=uh(this.y);return e[31]|=this.x&$e?128:0,e}toHex(){return lh(this.toRawBytes())}toX25519(){let{y:e}=this,t=V(($e+e)*Hp($e-e));return uh(t)}isTorsionFree(){return rr.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new r(V(-this.x),this.y)}add(e){return rr.fromAffine(this).add(rr.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return rr.fromAffine(this).multiply(e,this).toAffine()}};Ht.BASE=new Ht(Et.Gx,Et.Gy);Ht.ZERO=new Ht(fr,$e);var ch=class r{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){let t=Vo(e,64),n=Ht.fromHex(t.slice(0,32),!1),i=fh(t.slice(32,64));return new r(n,i)}assertValidity(){let{r:e,s:t}=this;if(!(e instanceof Ht))throw new Error("Expected Point instance");return $p(t,Et.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(uh(this.s),32),e}toHex(){return lh(this.toRawBytes())}};function bC(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function lh(r){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t=fr?t:e+t}function Hp(r,e=Et.P){if(r===fr||e<=fr)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=V(r,e),n=e,i=fr,s=$e,o=$e,a=fr;for(;t!==fr;){let u=n/t,l=n%t,f=i-o*u,h=s-a*u;n=t,t=l,i=o,s=a,o=f,a=h}if(n!==$e)throw new Error("invert: does not exist");return V(i,e)}function rX(r,e=Et.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===fr?s:(t[a]=s,V(s*o,e)),$e),i=Hp(n,e);return r.reduceRight((s,o,a)=>o===fr?s:(t[a]=V(s*t[a],e),V(s*o,e)),i),t}function ss(r,e){let{P:t}=Et,n=r;for(;e-- >fr;)n*=n,n%=t;return n}function nX(r){let{P:e}=Et,t=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=r*r%e*r%e,u=ss(c,Ko)*c%e,l=ss(u,$e)*r%e,f=ss(l,t)*l%e,h=ss(f,n)*f%e,d=ss(h,i)*h%e,p=ss(d,s)*d%e,m=ss(p,o)*p%e,g=ss(m,o)*p%e,y=ss(g,n)*f%e;return{pow_p_5_8:ss(y,Ko)*r%e,b2:c}}function J8(r,e){let t=V(e*e*e),n=V(t*t*e),i=nX(r*n).pow_p_5_8,s=V(r*t*i),o=V(e*s*s),a=s,c=V(s*ah),u=o===r,l=o===V(-r),f=o===V(-r*ah);return u&&(s=a),(l||f)&&(s=c),Fo(s)&&(s=V(-s)),{isValid:u||l,value:s}}function wC(r){return J8($e,r)}function zp(r){return V(fh(r),Et.l)}function iX(r,e){if(r.length!==e.length)return!1;for(let t=0;t{if(r=Vo(r),r.length<40||r.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return V(fh(r),Et.l-$e)+$e},randomBytes:(r=32)=>{if(Uo.web)return Uo.web.getRandomValues(new Uint8Array(r));if(Uo.node){let{randomBytes:e}=Uo.node;return new Uint8Array(e(r).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>qo.randomBytes(32),sha512:async(...r)=>{let e=bC(...r);if(Uo.web){let t=await Uo.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(t)}else{if(Uo.node)return Uint8Array.from(Uo.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(r=8,e=Ht.BASE){let t=e.equals(Ht.BASE)?e:new Ht(e.x,e.y);return t._setWindowSize(r),t.multiply(Ko),t},sha512Sync:void 0};Object.defineProperties(qo,{sha512Sync:{configurable:!1,get(){return X8},set(r){X8||(X8=r)}}});var qu=32,qs=64,Wp=32;async function SC(){let r=qo.randomPrivateKey(),e=await e5(r);return{privateKey:TC(r,e),publicKey:e}}async function RC(r){if(r.length!==Wp)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=await e5(e);return{privateKey:TC(e,t),publicKey:t}}async function IC(r,e){let t=r.subarray(0,Wp);return vC(e,t)}async function AC(r,e,t){return _C(e,t,r)}function TC(r,e){let t=new Uint8Array(qs);for(let n=0;nzu,base64pad:()=>hX,base64url:()=>dX,base64urlpad:()=>pX});var zu=Mt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hX=Mt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dX=Mt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pX=Mt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rn={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var r5={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function n5(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,i=r?.digest??"SHA-256",s=r?.saltLength??16,o=r?.iterations??32767,a=rn.get();t*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof h=="string"&&(h=G(h));let g;if(h.length===0){g=await a.subtle.importKey("jwk",r5,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",r5,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,f);return ve([d,m.iv,new Uint8Array(y)])}async function u(f,h){let d=f.subarray(0,s),p=f.subarray(s,s+n),m=f.subarray(s+n),g={name:e,iv:p};typeof h=="string"&&(h=G(h));let y;if(h.length===0)try{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,_,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",r5,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},_=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,_,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,y,m);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function $u(r,e){let n=await n5().encrypt(r,e);return zu.encode(n)}var Gt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Gt||(Gt={}));var i5;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(i5||(i5={}));(function(r){r.codec=()=>ft(i5)})(Gt||(Gt={}));var os;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Gt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Gt.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(os||(os={}));var zs;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Gt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.Type=Gt.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(zs||(zs={}));var hh=class{_key;constructor(e){this._key=Hu(e,qu)}async verify(e,t){return AC(this._key,t,e)}marshal(){return this._key}get bytes(){return os.encode({Type:Gt.Ed25519,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ir.digest(this.bytes);return e}},ja=class{_key;_publicKey;constructor(e,t){this._key=Hu(e,qs),this._publicKey=Hu(t,qu)}async sign(e){return IC(this._key,e)}get public(){return new hh(this._publicKey)}marshal(){return this._key}get bytes(){return zs.encode({Type:Gt.Ed25519,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ir.digest(this.bytes);return e}async id(){let e=Mo.digest(this.public.bytes);return Rr.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return $u(this.bytes,e);throw new ut(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function mX(r){if(r.length>qs){r=Hu(r,qs+qu);let n=r.subarray(0,qs),i=r.subarray(qs,r.length);return new ja(n,i)}r=Hu(r,qs);let e=r.subarray(0,qs),t=r.subarray(qu);return new ja(e,t)}function gX(r){return r=Hu(r,qu),new hh(r)}async function yX(){let{privateKey:r,publicKey:e}=await SC();return new ja(r,e)}async function CC(r){let{privateKey:e,publicKey:t}=await RC(r);return new ja(e,t)}function Hu(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ut(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var Tve=j(Nt(),1),Dve=j(Gl(),1),PC=j(Ve(),1);function Ci(r,e){let t=Uint8Array.from(r.abs().toByteArray());if(t=t[0]===0?t.subarray(1):t,e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=ve([new Uint8Array(e-t.length),t])}return U(t,"base64url")}function In(r){let e=kC(r);return new PC.default.jsbn.BigInteger(U(e,"base16"),16)}function kC(r,e){let t=G(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=ve([new Uint8Array(e-t.length),t])}return t}var bX={"P-256":256,"P-384":384,"P-521":521},wX=Object.keys(bX),Kve=wX.join(" / ");var p5={};be(p5,{RsaPrivateKey:()=>Ju,RsaPublicKey:()=>bh,fromJwk:()=>$X,generateKeyPair:()=>HX,unmarshalRsaPrivateKey:()=>qX,unmarshalRsaPublicKey:()=>zX});var yh=j(Ve(),1);var __e=j(c4(),1);var xX=j(ba(),1);var He=BigInt(0),xt=BigInt(1),$o=BigInt(2),ph=BigInt(3),NC=BigInt(8),Ut=Object.freeze({a:He,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:xt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),OC=(r,e)=>(r+e/$o)/e,Qp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(r){let{n:e}=Ut,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xt*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=OC(s*r,e),c=OC(-n*r,e),u=se(r-a*t-c*i,e),l=se(-a*n-c*s,e),f=u>o,h=l>o;if(f&&(u=e-u),h&&(l=e-l),u>o||l>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:h,k2:l}}},Pi=32,Qu=32,vX=32,BC=Pi+1,LC=2*Pi+1;function MC(r){let{a:e,b:t}=Ut,n=se(r*r),i=se(n*r);return se(i+e*r+t)}var Xp=Ut.a===He,Jp=class extends Error{constructor(e){super(e)}};function UC(r){if(!(r instanceof Hr))throw new TypeError("JacobianPoint expected")}var Hr=class r{constructor(e,t,n){this.x=e,this.y=t,this.z=n}static fromAffine(e){if(!(e instanceof Dt))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Dt.ZERO)?r.ZERO:new r(e.x,e.y,xt)}static toAffineBatch(e){let t=AX(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return r.toAffineBatch(e).map(r.fromAffine)}equals(e){UC(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=se(i*i),u=se(a*a),l=se(t*u),f=se(s*c),h=se(se(n*a)*u),d=se(se(o*i)*c);return l===f&&h===d}negate(){return new r(this.x,se(-this.y),this.z)}double(){let{x:e,y:t,z:n}=this,i=se(e*e),s=se(t*t),o=se(s*s),a=e+s,c=se($o*(se(a*a)-i-o)),u=se(ph*i),l=se(u*u),f=se(l-$o*c),h=se(u*(c-f)-NC*o),d=se($o*t*n);return new r(f,h,d)}add(e){UC(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===He||o===He)return this;if(t===He||n===He)return e;let c=se(i*i),u=se(a*a),l=se(t*u),f=se(s*c),h=se(se(n*a)*u),d=se(se(o*i)*c),p=se(f-l),m=se(d-h);if(p===He)return m===He?this.double():r.ZERO;let g=se(p*p),y=se(p*g),b=se(l*g),E=se(m*m-y-$o*b),_=se(m*(b-E)-h*y),x=se(i*a*p);return new r(E,_,x)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=r.ZERO;if(typeof e=="bigint"&&e===He)return t;let n=VC(e);if(n===xt)return this;if(!Xp){let f=t,h=this;for(;n>He;)n&xt&&(f=f.add(h)),h=h.double(),n>>=xt;return f}let{k1neg:i,k1:s,k2neg:o,k2:a}=Qp.splitScalar(n),c=t,u=t,l=this;for(;s>He||a>He;)s&xt&&(c=c.add(l)),a&xt&&(u=u.add(l)),l=l.double(),s>>=xt,a>>=xt;return i&&(c=c.negate()),o&&(u=u.negate()),u=new r(se(u.x*Qp.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let t=Xp?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o>=f,p>c&&(p-=l,e+=xt);let m=d,g=d+Math.abs(p)-1,y=h%2!==0,b=p<0;p===0?o=o.add(jp(y,i[m])):s=s.add(jp(b,i[g]))}return{p:s,f:o}}multiply(e,t){let n=VC(e),i,s;if(Xp){let{k1neg:o,k1:a,k2neg:c,k2:u}=Qp.splitScalar(n),{p:l,f}=this.wNAF(a,t),{p:h,f:d}=this.wNAF(u,t);l=jp(o,l),h=jp(c,h),h=new r(se(h.x*Qp.beta),h.y,h.z),i=l.add(h),s=f.add(d)}else{let{p:o,f:a}=this.wNAF(n,t);i=o,s=a}return r.normalizeZ([i,s])[0]}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(r.ZERO);e==null&&(e=s?NC:Zu(i));let o=e,a=se(o*o),c=se(a*o),u=se(t*a),l=se(n*c),f=se(i*o);if(s)return Dt.ZERO;if(f!==xt)throw new Error("invZ was invalid");return new Dt(u,l)}};Hr.BASE=new Hr(Ut.Gx,Ut.Gy,xt);Hr.ZERO=new Hr(He,xt,He);function jp(r,e){let t=e.negate();return r?t:e}var a5=new WeakMap,Dt=class r{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,a5.delete(this)}hasEvenY(){return this.y%$o===He}static fromCompressedHex(e){let t=e.length===32,n=Ho(t?e:e.subarray(1));if(!o5(n))throw new Error("Point is not on curve");let i=MC(n),s=IX(i),o=(s&xt)===xt;t?o&&(s=se(-s)):(e[0]&1)===1!==o&&(s=se(-s));let a=new r(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let t=Ho(e.subarray(1,Pi+1)),n=Ho(e.subarray(Pi+1,Pi*2+1)),i=new r(t,n);return i.assertValidity(),i}static fromHex(e){let t=ju(e),n=t.length,i=t[0];if(n===Pi)return this.fromCompressedHex(t);if(n===BC&&(i===2||i===3))return this.fromCompressedHex(t);if(n===LC&&i===4)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${BC} compressed bytes or ${LC} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return r.BASE.multiply(t2(e))}static fromSignature(e,t,n){let{r:i,s}=qC(t);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=l5(ju(e)),{n:a}=Ut,c=n===2||n===3?i+a:i,u=Zu(c,a),l=se(-o*u,a),f=se(s*u,a),h=n&1?"03":"02",d=r.fromHex(h+Wu(c)),p=r.BASE.multiplyAndAddUnsafe(d,l,f);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Za(this.toHex(e))}toHex(e=!1){let t=Wu(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Wu(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:n}=this;if(!o5(t)||!o5(n))throw new Error(e);let i=se(n*n),s=MC(t);if(se(i-s)!==He)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new r(this.x,se(-this.y))}double(){return Hr.fromAffine(this).double().toAffine()}add(e){return Hr.fromAffine(this).add(Hr.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Hr.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,n){let i=Hr.fromAffine(this),s=t===He||t===xt||this!==r.BASE?i.multiplyUnsafe(t):i.multiply(t),o=Hr.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(Hr.ZERO)?void 0:a.toAffine()}};Dt.BASE=new Dt(Ut.Gx,Ut.Gy);Dt.ZERO=new Dt(He,He);function FC(r){return Number.parseInt(r[0],16)>=8?"00"+r:r}function KC(r){if(r.length<2||r[0]!==2)throw new Error(`Invalid signature integer tag: ${Xu(r)}`);let e=r[1],t=r.subarray(2,e+2);if(!e||t.length!==e)throw new Error("Invalid signature integer: wrong length");if(t[0]===0&&t[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Ho(t),left:r.subarray(e+2)}}function _X(r){if(r.length<2||r[0]!=48)throw new Error(`Invalid signature tag: ${Xu(r)}`);if(r[1]!==r.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:t}=KC(r.subarray(2)),{data:n,left:i}=KC(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${Xu(i)}`);return{r:e,s:n}}var Gu=class r{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!t)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=t?Xu(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new r(e2(i.slice(0,64)),e2(i.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if(typeof e!="string"&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=_X(t?e:Za(e));return new r(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!gh(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!gh(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Ut.n>>xt;return this.s>e}normalizeS(){return this.hasHighS()?new r(this.r,se(-this.s,Ut.n)):this}toDERRawBytes(){return Za(this.toDERHex())}toDERHex(){let e=FC(dh(this.s)),t=FC(dh(this.r)),n=e.length/2,i=t.length/2,s=dh(n),o=dh(i);return`30${dh(i+n+4)}02${o}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Za(this.toCompactHex())}toCompactHex(){return Wu(this.r)+Wu(this.s)}};function zo(...r){if(!r.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(r.length===1)return r[0];let e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);for(let n=0,i=0;ne.toString(16).padStart(2,"0"));function Xu(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;t0)return BigInt(r);if(typeof r=="bigint"&&gh(r))return r;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function se(r,e=Ut.P){let t=r%e;return t>=He?t:e+t}function ei(r,e){let{P:t}=Ut,n=r;for(;e-- >He;)n*=n,n%=t;return n}function IX(r){let{P:e}=Ut,t=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=r*r*r%e,u=c*c*r%e,l=ei(u,ph)*u%e,f=ei(l,ph)*u%e,h=ei(f,$o)*c%e,d=ei(h,n)*h%e,p=ei(d,i)*d%e,m=ei(p,o)*p%e,g=ei(m,a)*m%e,y=ei(g,o)*p%e,b=ei(y,ph)*u%e,E=ei(b,s)*d%e,_=ei(E,t)*c%e,x=ei(_,$o);if(x*x%e!==r)throw new Error("Cannot find square root");return x}function Zu(r,e=Ut.P){if(r===He||e<=He)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=se(r,e),n=e,i=He,s=xt,o=xt,a=He;for(;t!==He;){let u=n/t,l=n%t,f=i-o*u,h=s-a*u;n=t,t=l,i=o,s=a,o=f,a=h}if(n!==xt)throw new Error("invert: does not exist");return se(i,e)}function AX(r,e=Ut.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===He?s:(t[a]=s,se(s*o,e)),xt),i=Zu(n,e);return r.reduceRight((s,o,a)=>o===He?s:(t[a]=se(s*t[a],e),se(s*o,e)),i),t}function TX(r){let e=r.length*8-Qu*8,t=Ho(r);return e>0?t>>BigInt(e):t}function l5(r,e=!1){let t=TX(r);if(e)return t;let{n}=Ut;return t>=n?t-n:t}var Yu,mh,u5=class{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||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 ki.hmacSha256(this.k,...e)}hmacSync(...e){return mh(this.k,...e)}checkSync(){if(typeof mh!="function")throw new Jp("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),e.length!==0&&(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),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e0)e=BigInt(r);else if(typeof r=="string"){if(r.length!==2*Qu)throw new Error("Expected 32 bytes of private key");e=e2(r)}else if(r instanceof Uint8Array){if(r.length!==Qu)throw new Error("Expected 32 bytes of private key");e=Ho(r)}else throw new TypeError("Expected valid private key");if(!gh(e))throw new Error("Expected private key: 0 < key < n");return e}function CX(r){return r instanceof Dt?(r.assertValidity(),r):Dt.fromHex(r)}function qC(r){if(r instanceof Gu)return r.assertValidity(),r;try{return Gu.fromDER(r)}catch{return Gu.fromCompact(r)}}function f5(r,e=!1){return Dt.fromPrivateKey(r).toRawBytes(e)}function zC(r){let e=r.length>Pi?r.slice(0,Pi):r;return Ho(e)}function PX(r){let e=zC(r),t=se(e,Ut.n);return $C(t{r=ju(r);let e=Qu+8;if(r.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let t=se(Ho(r),Ut.n-xt)+xt;return c5(t)},randomBytes:(r=32)=>{if(An.web)return An.web.getRandomValues(new Uint8Array(r));if(An.node){let{randomBytes:e}=An.node;return Uint8Array.from(e(r))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>ki.hashToPrivateKey(ki.randomBytes(Qu+8)),precompute(r=8,e=Dt.BASE){let t=e===Dt.BASE?e:new Dt(e.x,e.y);return t._setWindowSize(r),t.multiply(ph),t},sha256:async(...r)=>{if(An.web){let e=await An.web.subtle.digest("SHA-256",zo(...r));return new Uint8Array(e)}else if(An.node){let{createHash:e}=An.node,t=e("sha256");return r.forEach(n=>t.update(n)),Uint8Array.from(t.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(r,...e)=>{if(An.web){let t=await An.web.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=zo(...e),i=await An.web.subtle.sign("HMAC",t,n);return new Uint8Array(i)}else if(An.node){let{createHmac:t}=An.node,n=t("sha256",r);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(r,...e)=>{let t=Zp[r];if(t===void 0){let n=await ki.sha256(Uint8Array.from(r,i=>i.charCodeAt(0)));t=zo(n,n),Zp[r]=t}return ki.sha256(t,...e)},taggedHashSync:(r,...e)=>{if(typeof Yu!="function")throw new Jp("sha256Sync is undefined, you need to set it");let t=Zp[r];if(t===void 0){let n=Yu(Uint8Array.from(r,i=>i.charCodeAt(0)));t=zo(n,n),Zp[r]=t}return Yu(t,...e)},_JacobianPoint:Hr};Object.defineProperties(ki,{sha256Sync:{configurable:!1,get(){return Yu},set(r){Yu||(Yu=r)}},hmacSha256Sync:{configurable:!1,get(){return mh},set(r){mh||(mh=r)}}});function r2(r){if(isNaN(r)||r<=0)throw new ut("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ki.randomBytes(r)}var s_e=j(Dc(),1),h5=j(Ve(),1);function WC(r,e){return e.map(t=>In(r[t]))}function YC(r){return h5.default.pki.setRsaPrivateKey(...WC(r,["n","e","d","p","q","dp","dq","qi"]))}function QC(r){return h5.default.pki.setRsaPublicKey(...WC(r,["n","e"]))}var Ja={};be(Ja,{jwkToPkcs1:()=>MX,jwkToPkix:()=>FX,pkcs1ToJwk:()=>LX,pkixToJwk:()=>UX});var c_e=j(ma(),1),u_e=j(Dc(),1);var $s=j(Ve(),1);function LX(r){let e=$s.default.asn1.fromDer(U(r,"ascii")),t=$s.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Ci(t.n),e:Ci(t.e),d:Ci(t.d),p:Ci(t.p),q:Ci(t.q),dp:Ci(t.dP),dq:Ci(t.dQ),qi:Ci(t.qInv),alg:"RS256"}}function MX(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new ut("JWK was missing components","ERR_INVALID_PARAMETERS");let e=$s.default.pki.privateKeyToAsn1({n:In(r.n),e:In(r.e),d:In(r.d),p:In(r.p),q:In(r.q),dP:In(r.dp),dQ:In(r.dq),qInv:In(r.qi)});return G($s.default.asn1.toDer(e).getBytes(),"ascii")}function UX(r){let e=$s.default.asn1.fromDer(U(r,"ascii")),t=$s.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Ci(t.n),e:Ci(t.e)}}function FX(r){if(r.n==null||r.e==null)throw new ut("JWK was missing components","ERR_INVALID_PARAMETERS");let e=$s.default.pki.publicKeyToAsn1({n:In(r.n),e:In(r.e)});return G($s.default.asn1.toDer(e).getBytes(),"ascii")}async function XC(r){let e=await rn.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await JC(e);return{privateKey:t[0],publicKey:t[1]}}async function d5(r){let t=[await rn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await KX(r)],n=await JC({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function jC(r,e){let t=await rn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await rn.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function ZC(r,e,t){let n=await rn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return rn.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function JC(r){if(r.privateKey==null||r.publicKey==null)throw new ut("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([rn.get().subtle.exportKey("jwk",r.privateKey),rn.get().subtle.exportKey("jwk",r.publicKey)])}async function KX(r){return rn.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function eP(r,e,t,n){let i=e?QC(r):YC(r),s=U(Uint8Array.from(t),"ascii"),o=n(s,i);return G(o,"ascii")}function tP(r,e){return eP(r,!0,e,(t,n)=>n.encrypt(t))}function rP(r,e){return eP(r,!1,e,(t,n)=>n.decrypt(t))}var bh=class{_key;constructor(e){this._key=e}async verify(e,t){return ZC(this._key,t,e)}marshal(){return Ja.jwkToPkix(this._key)}get bytes(){return os.encode({Type:Gt.RSA,Data:this.marshal()}).subarray()}encrypt(e){return tP(this._key,e)}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ir.digest(this.bytes);return e}},Ju=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return r2(16)}async sign(e){return jC(this._key,e)}get public(){if(this._publicKey==null)throw new ut("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new bh(this._publicKey)}decrypt(e){return rP(this._key,e)}marshal(){return Ja.jwkToPkcs1(this._key)}get bytes(){return zs.encode({Type:Gt.RSA,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ir.digest(this.bytes);return e}async id(){let e=await this.public.hash();return U(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new yh.default.util.ByteBuffer(this.marshal()),i=yh.default.asn1.fromDer(n),s=yh.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return yh.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(t==="libp2p-key")return $u(this.bytes,e);throw new ut(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function qX(r){let e=Ja.pkcs1ToJwk(r),t=await d5(e);return new Ju(t.privateKey,t.publicKey)}function zX(r){let e=Ja.pkixToJwk(r);return new bh(e)}async function $X(r){let e=await d5(r);return new Ju(e.privateKey,e.publicKey)}async function HX(r){let e=await XC(r);return new Ju(e.privateKey,e.publicKey)}var g5={};be(g5,{Secp256k1PrivateKey:()=>Eh,Secp256k1PublicKey:()=>wh,generateKeyPair:()=>QX,unmarshalSecp256k1PrivateKey:()=>WX,unmarshalSecp256k1PublicKey:()=>YX});function nP(){return ki.randomPrivateKey()}async function iP(r,e){let{digest:t}=await Ir.digest(e);try{return await HC(t,r)}catch(n){throw new ut(String(n),"ERR_INVALID_INPUT")}}async function sP(r,e,t){try{let{digest:n}=await Ir.digest(t);return GC(e,n,r)}catch(n){throw new ut(String(n),"ERR_INVALID_INPUT")}}function oP(r){return Dt.fromHex(r).toRawBytes(!0)}function aP(r){try{f5(r,!0)}catch(e){throw new ut(String(e),"ERR_INVALID_PRIVATE_KEY")}}function m5(r){try{Dt.fromHex(r)}catch(e){throw new ut(String(e),"ERR_INVALID_PUBLIC_KEY")}}function cP(r){try{return f5(r,!0)}catch(e){throw new ut(String(e),"ERR_INVALID_PRIVATE_KEY")}}var wh=class{_key;constructor(e){m5(e),this._key=e}async verify(e,t){return sP(this._key,t,e)}marshal(){return oP(this._key)}get bytes(){return os.encode({Type:Gt.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ir.digest(this.bytes);return e}},Eh=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??cP(e),aP(this._key),m5(this._publicKey)}async sign(e){return iP(this._key,e)}get public(){return new wh(this._publicKey)}marshal(){return this._key}get bytes(){return zs.encode({Type:Gt.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return fe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Ir.digest(this.bytes);return e}async id(){let e=await this.public.hash();return U(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return $u(this.bytes,e);throw new ut(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function WX(r){return new Eh(r)}function YX(r){return new wh(r)}async function QX(){let r=nP();return new Eh(r)}var n2={rsa:p5,ed25519:s5,secp256k1:g5};function jX(r){let e=Object.keys(n2).join(" / ");return new ut(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function y5(r){let e=os.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Gt.RSA:return n2.rsa.unmarshalRsaPublicKey(t);case Gt.Ed25519:return n2.ed25519.unmarshalEd25519PublicKey(t);case Gt.Secp256k1:return n2.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw jX(e.Type??"RSA")}}var Tn=j(Uh(),1);var b5={};be(b5,{base32:()=>Go,base32hex:()=>tj,base32hexpad:()=>nj,base32hexpadupper:()=>ij,base32hexupper:()=>rj,base32pad:()=>JX,base32padupper:()=>ej,base32upper:()=>ZX,base32z:()=>sj});var Go=Mt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZX=Mt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),JX=Mt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ej=Mt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),tj=Mt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),rj=Mt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),nj=Mt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ij=Mt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sj=Mt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});Tn.default.formatters.b=r=>r==null?"undefined":Rr.baseEncode(r);Tn.default.formatters.t=r=>r==null?"undefined":Go.baseEncode(r);Tn.default.formatters.m=r=>r==null?"undefined":zu.baseEncode(r);Tn.default.formatters.p=r=>r==null?"undefined":r.toString();Tn.default.formatters.c=r=>r==null?"undefined":r.toString();Tn.default.formatters.k=r=>r==null?"undefined":r.toString();Tn.default.formatters.a=r=>r==null?"undefined":r.toString();function oj(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function i2(r){let e=oj(`${r}:trace`);return Tn.default.enabled(`${r}:trace`)&&Tn.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Tn.default)(`${r}:trace`)),Object.assign((0,Tn.default)(r),{error:(0,Tn.default)(`${r}:error`),trace:e})}var uP=Symbol.for("@libp2p/peer-id");var w5={};be(w5,{identity:()=>aj});var aj=Mu({prefix:"\0",name:"identity",encode:r=>iC(r),decode:r=>nC(r)});var E5={};be(E5,{base2:()=>cj});var cj=Mt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var x5={};be(x5,{base8:()=>uj});var uj=Mt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var v5={};be(v5,{base10:()=>lj});var lj=Lo({prefix:"9",name:"base10",alphabet:"0123456789"});var _5={};be(_5,{base16:()=>fj,base16upper:()=>hj});var fj=Mt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hj=Mt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var S5={};be(S5,{base36:()=>dj,base36upper:()=>pj});var dj=Lo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pj=Lo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var R5={};be(R5,{base256emoji:()=>wj});var lP=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),mj=lP.reduce((r,e,t)=>(r[t]=e,r),[]),gj=lP.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function yj(r){return r.reduce((e,t)=>(e+=mj[t],e),"")}function bj(r){let e=[];for(let t of r){let n=gj[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var wj=Mu({prefix:"\u{1F680}",name:"base256emoji",encode:yj,decode:bj});var sSe=new TextEncoder,oSe=new TextDecoder;var fP=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return _j(t,I5(r),e||Rr.encoder);default:return Sj(t,I5(r),e||Go.encoder)}};var hP=new WeakMap,I5=r=>{let e=hP.get(r);if(e==null){let t=new Map;return hP.set(r,t),t}return e},ec=class r{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==xh)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Rj)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=is(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&lC(e.multihash,n.multihash)}toString(e){return fP(this,e)}toJSON(){return{"/":fP(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new r(n,i,s,o||dP(n,i,s.bytes))}else if(t[Ij]===!0){let{version:n,multihash:i,code:s}=t,o=oh(i);return r.create(n,s,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==xh)throw new Error(`Version 0 CID must use dag-pb (code: ${xh}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=dP(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,xh,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=Vs(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new Ku(t.multihashCode,t.digestSize,s,i);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=sh(e.subarray(t));return t+=h,f},i=n(),s=xh;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),u=t+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=vj(e,t),s=r.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return I5(s).set(n,e),s}},vj=(r,e)=>{switch(r[0]){case"Q":{let t=e||Rr;return[Rr.prefix,t.decode(`${Rr.prefix}${r}`)]}case Rr.prefix:{let t=e||Rr;return[Rr.prefix,t.decode(r)]}case Go.prefix:{let t=e||Go;return[Go.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},_j=(r,e,t)=>{let{prefix:n}=t;if(n!==Rr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},Sj=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},xh=112,Rj=18,dP=(r,e,t)=>{let n=Fu(r),i=n+Fu(e),s=new Uint8Array(i+t.byteLength);return Uu(r,s,0),Uu(e,s,n),s.set(t,i),s},Ij=Symbol.for("@ipld/js-cid/CID");var A5={...w5,...E5,...x5,...v5,..._5,...b5,...S5,...V8,...t5,...R5},gSe={...G8,...z8};var Aj=Symbol.for("nodejs.util.inspect.custom"),pP=Object.values(A5).map(r=>r.decoder).reduce((r,e)=>r.or(e),A5.identity.decoder),mP=114,T5=36,D5=37,vh=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[uP]=!0;toString(){return this.string==null&&(this.string=Rr.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ec.createV1(mP,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return fe(this.multihash.bytes,e);if(typeof e=="string")return Tj(e).equals(this);if(e?.multihash?.bytes!=null)return fe(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Aj](){return`PeerId(${this.toString()})`}},el=class extends vh{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},tl=class extends vh{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},rl=class extends vh{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Tj(r,e){if(e=e??pP,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=oh(Rr.decode(`z${r}`));return r.startsWith("12D")?new tl({multihash:t}):r.startsWith("16U")?new rl({multihash:t}):new el({multihash:t})}return C5(pP.decode(r))}function C5(r){try{let e=oh(r);if(e.code===Mo.code){if(e.digest.length===T5)return new tl({multihash:e});if(e.digest.length===D5)return new rl({multihash:e})}if(e.code===Ir.code)return new el({multihash:e})}catch{return Dj(ec.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Dj(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==mP)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ir.code)return new el({multihash:r.multihash});if(e.code===Mo.code){if(e.digest.length===T5)return new tl({multihash:r.multihash});if(e.digest.length===D5)return new rl({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function gP(r,e){return r.length===T5?new tl({multihash:is(Mo.code,r),privateKey:e}):r.length===D5?new rl({multihash:is(Mo.code,r),privateKey:e}):new el({multihash:await Ir.digest(r),publicKey:r,privateKey:e})}var Cj=["string","number","bigint","symbol"],Pj=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function yP(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(Cj.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(kj(r))return"Buffer";let t=Nj(r);return t||"Object"}function kj(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Nj(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Pj.includes(e))return e}var L=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}};L.uint=new L(0,"uint",!0);L.negint=new L(1,"negint",!0);L.bytes=new L(2,"bytes",!0);L.string=new L(3,"string",!0);L.array=new L(4,"array",!1);L.map=new L(5,"map",!1);L.tag=new L(6,"tag",!1);L.float=new L(7,"float",!0);L.false=new L(7,"false",!0);L.true=new L(7,"true",!0);L.null=new L(7,"null",!0);L.undefined=new L(7,"undefined",!0);L.break=new L(7,"break",!0);var oe=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var nl=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Oj=new TextDecoder,Bj=new TextEncoder;function s2(r){return nl&&globalThis.Buffer.isBuffer(r)}function xP(r){return r instanceof Uint8Array?s2(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var vP=nl?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):wP(r,e,t):(r,e,t)=>t-e>64?Oj.decode(r.subarray(e,t)):wP(r,e,t),_P=nl?r=>r.length>64?globalThis.Buffer.from(r):bP(r):r=>r.length>64?Bj.encode(r):bP(r);var il=nl?(r,e,t)=>s2(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),SP=nl?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),xP(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},RP=nl?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function IP(r,e){if(s2(r)&&s2(e))return r.compare(e);for(let t=0;t55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function wP(r,e,t){let n=[];for(;e239?4:i>223?3:i>191?2:1;if(e+o<=t){let a,c,u,l;switch(o){case 1:i<128&&(s=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(s=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(i&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(s=l))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=o}return Lj(n)}var EP=4096;function Lj(r){let e=r.length;if(e<=EP)return String.fromCharCode.apply(String,r);let t="",n=0;for(;nn.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=il(n,0,this.cursor)}else t=SP(this.chunks,this.cursor);return e&&this.reset(),t}};var Ie="CBOR decode error:",P5="CBOR encode error:",_h=[];_h[23]=1;_h[24]=2;_h[25]=3;_h[26]=5;_h[27]=9;function Hs(r,e,t){if(r.length-e>>8,n&255])}else if(t>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${Ie} encountered BigInt larger than allowable range`)}}ti.encodedSize=function(e){return Ar.encodedSize(e.value)};Ar.encodedSize=function(e){return et.value?1:0};function PP(r,e,t,n){return new oe(L.negint,-1-Dn(r,e+1,n),2)}function kP(r,e,t,n){return new oe(L.negint,-1-Cn(r,e+1,n),3)}function NP(r,e,t,n){return new oe(L.negint,-1-Pn(r,e+1,n),5)}var k5=BigInt(-1),OP=BigInt(1);function BP(r,e,t,n){let i=kn(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new oe(L.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Ie} integers outside of the safe integer range are not supported`);return new oe(L.negint,k5-BigInt(i),9)}function a2(r,e){let t=e.value,n=typeof t=="bigint"?t*k5-OP:t*-1-1;Ar(r,e.type.majorEncoded,n)}a2.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*k5-OP:t*-1-1;return nt.value?-1:0};function Sh(r,e,t,n){Hs(r,e,t+n);let i=il(r,e+t,e+t+n);return new oe(L.bytes,i,t+n)}function LP(r,e,t,n){return Sh(r,e,1,t)}function MP(r,e,t,n){return Sh(r,e,2,Dn(r,e+1,n))}function UP(r,e,t,n){return Sh(r,e,3,Cn(r,e+1,n))}function FP(r,e,t,n){return Sh(r,e,5,Pn(r,e+1,n))}function KP(r,e,t,n){let i=kn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Ie} 64-bit integer bytes lengths not supported`);return Sh(r,e,9,i)}function c2(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===L.string?_P(r.value):r.value),r.encodedBytes}function sl(r,e){let t=c2(e);Ar(r,e.type.majorEncoded,t.length),r.push(t)}sl.encodedSize=function(e){let t=c2(e);return Ar.encodedSize(t.length)+t.length};sl.compareTokens=function(e,t){return Fj(c2(e),c2(t))};function Fj(r,e){return r.lengthe.length?1:IP(r,e)}function Rh(r,e,t,n,i){let s=t+n;Hs(r,e,s);let o=new oe(L.string,vP(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=il(r,e+t,e+s)),o}function VP(r,e,t,n){return Rh(r,e,1,t,n)}function qP(r,e,t,n){return Rh(r,e,2,Dn(r,e+1,n),n)}function zP(r,e,t,n){return Rh(r,e,3,Cn(r,e+1,n),n)}function $P(r,e,t,n){return Rh(r,e,5,Pn(r,e+1,n),n)}function HP(r,e,t,n){let i=kn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Ie} 64-bit integer string lengths not supported`);return Rh(r,e,9,i,n)}var GP=sl;function ol(r,e,t,n){return new oe(L.array,n,t)}function WP(r,e,t,n){return ol(r,e,1,t)}function YP(r,e,t,n){return ol(r,e,2,Dn(r,e+1,n))}function QP(r,e,t,n){return ol(r,e,3,Cn(r,e+1,n))}function XP(r,e,t,n){return ol(r,e,5,Pn(r,e+1,n))}function jP(r,e,t,n){let i=kn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Ie} 64-bit integer array lengths not supported`);return ol(r,e,9,i)}function ZP(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Ie} indefinite length items not allowed`);return ol(r,e,1,1/0)}function u2(r,e){Ar(r,L.array.majorEncoded,e.value)}u2.compareTokens=ti.compareTokens;u2.encodedSize=function(e){return Ar.encodedSize(e.value)};function al(r,e,t,n){return new oe(L.map,n,t)}function JP(r,e,t,n){return al(r,e,1,t)}function ek(r,e,t,n){return al(r,e,2,Dn(r,e+1,n))}function tk(r,e,t,n){return al(r,e,3,Cn(r,e+1,n))}function rk(r,e,t,n){return al(r,e,5,Pn(r,e+1,n))}function nk(r,e,t,n){let i=kn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Ie} 64-bit integer map lengths not supported`);return al(r,e,9,i)}function ik(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Ie} indefinite length items not allowed`);return al(r,e,1,1/0)}function l2(r,e){Ar(r,L.map.majorEncoded,e.value)}l2.compareTokens=ti.compareTokens;l2.encodedSize=function(e){return Ar.encodedSize(e.value)};function sk(r,e,t,n){return new oe(L.tag,t,1)}function ok(r,e,t,n){return new oe(L.tag,Dn(r,e+1,n),2)}function ak(r,e,t,n){return new oe(L.tag,Cn(r,e+1,n),3)}function ck(r,e,t,n){return new oe(L.tag,Pn(r,e+1,n),5)}function uk(r,e,t,n){return new oe(L.tag,kn(r,e+1,n),9)}function f2(r,e){Ar(r,L.tag.majorEncoded,e.value)}f2.compareTokens=ti.compareTokens;f2.encodedSize=function(e){return Ar.encodedSize(e.value)};var Hj=20,Gj=21,Wj=22,Yj=23;function lk(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Ie} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new oe(L.null,null,1):new oe(L.undefined,void 0,1)}function fk(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Ie} indefinite length items not allowed`);return new oe(L.break,void 0,1)}function N5(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Ie} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Ie} Infinity values are not supported`)}return new oe(L.float,r,e)}function hk(r,e,t,n){return N5(O5(r,e+1),3,n)}function dk(r,e,t,n){return N5(B5(r,e+1),5,n)}function pk(r,e,t,n){return N5(bk(r,e+1),9,n)}function h2(r,e,t){let n=e.value;if(n===!1)r.push([L.float.majorEncoded|Hj]);else if(n===!0)r.push([L.float.majorEncoded|Gj]);else if(n===null)r.push([L.float.majorEncoded|Wj]);else if(n===void 0)r.push([L.float.majorEncoded|Yj]);else{let i,s=!1;(!t||t.float64!==!0)&&(gk(n),i=O5(Ni,1),n===i||Number.isNaN(n)?(Ni[0]=249,r.push(Ni.slice(0,3)),s=!0):(yk(n),i=B5(Ni,1),n===i&&(Ni[0]=250,r.push(Ni.slice(0,5)),s=!0))),s||(Qj(n),i=bk(Ni,1),Ni[0]=251,r.push(Ni.slice(0,9)))}}h2.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){gk(n);let i=O5(Ni,1);if(n===i||Number.isNaN(n))return 3;if(yk(n),i=B5(Ni,1),n===i)return 5}return 9};var mk=new ArrayBuffer(9),ri=new DataView(mk,1),Ni=new Uint8Array(mk,0);function gk(r){if(r===1/0)ri.setUint16(0,31744,!1);else if(r===-1/0)ri.setUint16(0,64512,!1);else if(Number.isNaN(r))ri.setUint16(0,32256,!1);else{ri.setFloat32(0,r);let e=ri.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)ri.setUint16(0,31744,!1);else if(t===0)ri.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?ri.setUint16(0,0):i<-14?ri.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):ri.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function O5(r,e){if(r.length-e<2)throw new Error(`${Ie} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function yk(r){ri.setFloat32(0,r,!1)}function B5(r,e){if(r.length-e<4)throw new Error(`${Ie} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Qj(r){ri.setFloat64(0,r,!1)}function bk(r,e){if(r.length-e<8)throw new Error(`${Ie} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}h2.compareTokens=ti.compareTokens;function Ze(r,e,t){throw new Error(`${Ie} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function d2(r){return()=>{throw new Error(`${Ie} ${r}`)}}var J=[];for(let r=0;r<=23;r++)J[r]=Ze;J[24]=AP;J[25]=TP;J[26]=DP;J[27]=CP;J[28]=Ze;J[29]=Ze;J[30]=Ze;J[31]=Ze;for(let r=32;r<=55;r++)J[r]=Ze;J[56]=PP;J[57]=kP;J[58]=NP;J[59]=BP;J[60]=Ze;J[61]=Ze;J[62]=Ze;J[63]=Ze;for(let r=64;r<=87;r++)J[r]=LP;J[88]=MP;J[89]=UP;J[90]=FP;J[91]=KP;J[92]=Ze;J[93]=Ze;J[94]=Ze;J[95]=d2("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)J[r]=VP;J[120]=qP;J[121]=zP;J[122]=$P;J[123]=HP;J[124]=Ze;J[125]=Ze;J[126]=Ze;J[127]=d2("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)J[r]=WP;J[152]=YP;J[153]=QP;J[154]=XP;J[155]=jP;J[156]=Ze;J[157]=Ze;J[158]=Ze;J[159]=ZP;for(let r=160;r<=183;r++)J[r]=JP;J[184]=ek;J[185]=tk;J[186]=rk;J[187]=nk;J[188]=Ze;J[189]=Ze;J[190]=Ze;J[191]=ik;for(let r=192;r<=215;r++)J[r]=sk;J[216]=ok;J[217]=ak;J[218]=ck;J[219]=uk;J[220]=Ze;J[221]=Ze;J[222]=Ze;J[223]=Ze;for(let r=224;r<=243;r++)J[r]=d2("simple values are not supported");J[244]=Ze;J[245]=Ze;J[246]=Ze;J[247]=lk;J[248]=d2("simple values are not supported");J[249]=hk;J[250]=dk;J[251]=pk;J[252]=Ze;J[253]=Ze;J[254]=Ze;J[255]=fk;var Oi=[];for(let r=0;r<24;r++)Oi[r]=new oe(L.uint,r,1);for(let r=-1;r>=-24;r--)Oi[31-r]=new oe(L.negint,r,1);Oi[64]=new oe(L.bytes,new Uint8Array(0),1);Oi[96]=new oe(L.string,"",1);Oi[128]=new oe(L.array,0,1);Oi[160]=new oe(L.map,0,1);Oi[244]=new oe(L.false,!1,1);Oi[245]=new oe(L.true,!0,1);Oi[246]=new oe(L.null,null,1);function jj(){let r=[];return r[L.uint.major]=ti,r[L.negint.major]=a2,r[L.bytes.major]=sl,r[L.string.major]=GP,r[L.array.major]=u2,r[L.map.major]=l2,r[L.tag.major]=f2,r[L.float.major]=h2,r}var bRe=jj(),wRe=new o2,p2=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${P5} object contains circular references`);return new r(t,e)}},Wo={null:new oe(L.null,null),undefined:new oe(L.undefined,void 0),true:new oe(L.true,!0),false:new oe(L.false,!1),emptyArray:new oe(L.array,0),emptyMap:new oe(L.map,0)},Yo={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new oe(L.float,r):r>=0?new oe(L.uint,r):new oe(L.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new oe(L.uint,r):new oe(L.negint,r)},Uint8Array(r,e,t,n){return new oe(L.bytes,r)},string(r,e,t,n){return new oe(L.string,r)},boolean(r,e,t,n){return r?Wo.true:Wo.false},null(r,e,t,n){return Wo.null},undefined(r,e,t,n){return Wo.undefined},ArrayBuffer(r,e,t,n){return new oe(L.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new oe(L.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Wo.emptyArray,new oe(L.break)]:Wo.emptyArray;n=p2.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=L5(o,t,n);return t.addBreakTokens?[new oe(L.array,r.length),i,new oe(L.break)]:[new oe(L.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length;if(!o)return t.addBreakTokens===!0?[Wo.emptyMap,new oe(L.break)]:Wo.emptyMap;n=p2.createCheck(n,r);let a=[],c=0;for(let u of s)a[c++]=[L5(u,t,n),L5(i?r.get(u):r[u],t,n)];return Zj(a,t),t.addBreakTokens?[new oe(L.map,o),a,new oe(L.break)]:[new oe(L.map,o),a]}};Yo.Map=Yo.Object;Yo.Buffer=Yo.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Yo[`${r}Array`]=Yo.DataView;function L5(r,e={},t){let n=yP(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Yo[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=Yo[n];if(!s)throw new Error(`${P5} unsupported type: ${n}`);return s(r,n,e,t)}function Zj(r,e){e.mapSorter&&r.sort(e.mapSorter)}var Jj={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},M5=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],t=Oi[e];if(t===void 0){let n=J[e];if(!n)throw new Error(`${Ie} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this.pos,i,this.options)}return this.pos+=t.encodedLength,t}},Ih=Symbol.for("DONE"),m2=Symbol.for("BREAK");function eZ(r,e,t){let n=[];for(let i=0;i{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw Rk.error(n),(0,Th.default)(n,F5)}let t;if(e.pubKey!=null){try{t=y5(e.pubKey)}catch(i){throw Rk.error(i),i}if(!(await gP(e.pubKey)).equals(r))throw(0,Th.default)(new Error("Embedded public key did not match PeerID"),vk)}else r.publicKey!=null&&(t=y5(r.publicKey));if(t!=null)return t;throw(0,Th.default)(new Error("no public key is available"),F5)};var Ak=r=>{let e=G("ipns-signature:");return ve([e,r])};var Tk=r=>{let e=ns.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??ns.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var Dk=r=>C5(r.slice(iZ.length));var Ck=r=>{let e=U5(r);if(e.ValidityType===0)e.ValidityType=ns.ValidityType.EOL;else throw(0,Th.default)(new Error("Unknown validity type"),g2);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};var Pk=(r,e)=>{let t=e.map((n,i)=>({entry:ns.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let s=n.entry.sequence??0n,o=i.entry.sequence??0n;if(s>o)return-1;if(sl.getTime()?-1:u.getTime(){let{value:t,validityType:n,validity:i}=e,s,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,s=Ak(e.data),aZ(e);else throw(0,Nn.default)(new Error("missing data or signatureV2"),Qo);let a;try{a=await r.verify(s,o)}catch{a=!1}if(!a)throw Ch.error("record signature verification failed"),(0,Nn.default)(new Error("record signature verification failed"),Qo);if(i!=null&&n===ns.ValidityType.EOL){let c;try{c=Dh(U(i))}catch{throw Ch.error("unrecognized validity format (not an rfc3339 format)"),(0,Nn.default)(new Error("unrecognized validity format (not an rfc3339 format)"),Ek)}if(c.getTime(){if(r.data==null)throw(0,Nn.default)(new Error("Record data is missing"),xk);let e=Ck(r.data);if(!fe(e.Value,r.value))throw(0,Nn.default)(new Error('Field "value" did not match between protobuf and CBOR'),Qo);if(!fe(e.Validity,r.validity))throw(0,Nn.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Qo);if(e.ValidityType!==r.validityType)throw(0,Nn.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Qo);if(e.Sequence!==r.sequence)throw(0,Nn.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Qo);if(e.TTL!==r.ttl)throw(0,Nn.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Qo)},kk=async(r,e)=>{if(e.byteLength>sZ)throw(0,Nn.default)(new Error("record too large"),_k);let t=Dk(r),n=Tk(e),i=await Ik(t,n);await oZ(i,n)};var V5=j(Xr(),1);var Nk="libp2p",Ok="autonat",Bk="1.0.0";var Oe;(function(r){let e;(function(u){u.DIAL="DIAL",u.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(u){u[u.DIAL=0]="DIAL",u[u.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(u){u.codec=()=>ft(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(u){u.OK="OK",u.E_DIAL_ERROR="E_DIAL_ERROR",u.E_DIAL_REFUSED="E_DIAL_REFUSED",u.E_BAD_REQUEST="E_BAD_REQUEST",u.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(u){u[u.OK=0]="OK",u[u.E_DIAL_ERROR=100]="E_DIAL_ERROR",u[u.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",u[u.E_BAD_REQUEST=200]="E_BAD_REQUEST",u[u.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(u){u.codec=()=>ft(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(u){let l;u.codec=()=>(l==null&&(l=me((f,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),f.id!=null&&(h.uint32(10),h.bytes(f.id)),f.addrs!=null)for(let p of f.addrs)h.uint32(18),h.bytes(p);d.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let d={addrs:[]},p=h==null?f.len:f.pos+h;for(;f.pos>>3){case 1:d.id=f.bytes();break;case 2:d.addrs.push(f.bytes());break;default:f.skipType(m&7);break}}return d})),l),u.encode=f=>pe(f,u.codec()),u.decode=f=>de(f,u.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(u){let l;u.codec=()=>(l==null&&(l=me((f,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),f.peer!=null&&(h.uint32(10),r.PeerInfo.codec().encode(f.peer,h)),d.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let d={},p=h==null?f.len:f.pos+h;for(;f.pos>>3){case 1:d.peer=r.PeerInfo.codec().decode(f,f.uint32());break;default:f.skipType(m&7);break}}return d})),l),u.encode=f=>pe(f,u.codec()),u.decode=f=>de(f,u.codec())})(o=r.Dial||(r.Dial={}));let a;(function(u){let l;u.codec=()=>(l==null&&(l=me((f,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),f.status!=null&&(h.uint32(8),r.ResponseStatus.codec().encode(f.status,h)),f.statusText!=null&&(h.uint32(18),h.string(f.statusText)),f.addr!=null&&(h.uint32(26),h.bytes(f.addr)),d.lengthDelimited!==!1&&h.ldelim()},(f,h)=>{let d={},p=h==null?f.len:f.pos+h;for(;f.pos>>3){case 1:d.status=r.ResponseStatus.codec().decode(f);break;case 2:d.statusText=f.string();break;case 3:d.addr=f.bytes();break;default:f.skipType(m&7);break}}return d})),l),u.encode=f=>pe(f,u.codec()),u.decode=f=>de(f,u.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=me((u,l,f={})=>{f.lengthDelimited!==!1&&l.fork(),u.type!=null&&(l.uint32(8),r.MessageType.codec().encode(u.type,l)),u.dial!=null&&(l.uint32(18),r.Dial.codec().encode(u.dial,l)),u.dialResponse!=null&&(l.uint32(26),r.DialResponse.codec().encode(u.dialResponse,l)),f.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let f={},h=l==null?u.len:u.pos+l;for(;u.pos>>3){case 1:f.type=r.MessageType.codec().decode(u);break;case 2:f.dial=r.Dial.codec().decode(u,u.uint32());break;case 3:f.dialResponse=r.DialResponse.codec().decode(u,u.uint32());break;default:u.skipType(d&7);break}}return f})),c),r.encode=u=>pe(u,r.codec()),r.decode=u=>de(u,r.codec())})(Oe||(Oe={}));var Je=C("libp2p:autonat"),K5=4,q5=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??Nk}/${Ok}/${Bk}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Je.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=er([AbortSignal.timeout(this.timeout)]);try{(0,V5.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(i=>i.toOptions().host);try{let i=Ri(e.stream,t),s=this;await Me(i,o=>Yt(o),async function*(o){let a=await Ns(o);if(a==null){Je("no message received"),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=Oe.decode(a)}catch(m){Je.error("could not decode message",m),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let u=c.dial;if(u==null){Je.error("dial was missing from message"),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let l,f=u.peer;if(f==null||f.id==null){Je.error("PeerId missing from message"),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{l=Ot(f.id)}catch(m){Je.error("invalid PeerId",m),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Je("incoming request from %p",l),!e.connection.remotePeer.equals(l)){Je("target peer %p did not equal sending peer %p",l,e.connection.remotePeer),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let h=f.addrs.map(m=>ge(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Je.trace("request to dial %a was sent from %a is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(Jr(g)??!1);return Je.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Je.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Je.trace("transport for %a is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${l.toString()}`)),m));if(h.length===0){Je("no valid multiaddrs for %p in message",l),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Je("dial multiaddrs %s for peer %p",h.map(m=>m.toString()).join(", "),l);let d="",p=h[0];for await(let m of h){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Je.error("tried to dial %a but dialed %a",m,g.remoteAddr),new Error("Unexpected remote address");Je("Success %p",l),yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(le("p2p").code).bytes}});return}catch(y){Je("could not dial %p",l,y),d=y.message}finally{g!=null&&await g.close()}}yield Oe.encode({type:Oe.MessageType.DIAL_RESPONSE,dialResponse:{status:Oe.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>Kt(o),e.stream)}catch(i){Je.error("error handling incoming autonat stream",i)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Je.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(Jr(o.host)??!1)});if(t.length===0){Je("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,V5.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Je("verify multiaddrs %s",t.map(f=>f.toString()).join(", "));let s=Oe.encode({type:Oe.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(f=>f.bytes)}}}),a=(await Cd()).toBytes(),c={},u=[],l=async f=>{try{Je("asking %p to verify multiaddr",f.id);let h=await i.components.connectionManager.openConnection(f.id,{signal:n}),d=await h.newStream(this.protocol,{signal:n}),p=Ri(d,n),m=await Me([s],y=>Kt(y),p,y=>Yt(y),async y=>Ns(y));if(m==null){Je("no response received from %p",h.remotePeer);return}let g=Oe.decode(m);if(g.type!==Oe.MessageType.DIAL_RESPONSE||g.dialResponse==null){Je("invalid autonat response from %p",h.remotePeer);return}if(g.dialResponse.status===Oe.ResponseStatus.OK){let y=h.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Je('remote address "%s" was not IP4 or IP6?',y.host);return}if(u.includes(b)){Je("already have response from network segment %d - %s",b,y.host);return}u.push(b)}return g.dialResponse}catch(h){Je.error("error asking remote to verify multiaddr",h)}};for await(let f of $a(oi(this.components.peerRouting.getClosestPeers(a,{signal:n}),h=>async()=>l(h)),{concurrency:K5}))try{if(f==null)continue;let h=f.addr==null?t[0]:ge(f.addr);if(Je("autonat response for %a is %s",h,f.status),f.status===Oe.ResponseStatus.E_BAD_REQUEST||f.status===Oe.ResponseStatus.E_DIAL_REFUSED||f.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(h))){Je("peer reported %a as %s but it was not in our observed address list",h,f.status);continue}let d=h.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),f.status===Oe.ResponseStatus.OK?c[d].success++:f.status===Oe.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===K5){Je("%a is externally dialable",h),e.confirmObservedAddr(h);return}if(c[d].failure===K5){Je("%a is not externally dialable",h),e.removeObservedAddr(h);return}}catch(h){Je.error("could not verify external address",h)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function Lk(r={}){return e=>new q5(e,r)}var bZ=j(Xr(),1);var z5="/libp2p/relay";var Mk="circuit-relay-relay";var Uk=BigInt(131072),Xo="/libp2p/circuit/relay/0.2.0/hop",y2="/libp2p/circuit/relay/0.2.0/stop",dZ=30*1e3,pZ=30*1e3;var Gs;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>ft(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),cl.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),b2.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),ul.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),nr.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=cl.codec().decode(i,i.uint32());break;case 3:o.reservation=b2.codec().decode(i,i.uint32());break;case 4:o.limit=ul.codec().decode(i,i.uint32());break;case 5:o.status=nr.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(Gs||(Gs={}));var Bi;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>ft(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),cl.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),ul.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),nr.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=cl.codec().decode(i,i.uint32());break;case 3:o.limit=ul.codec().decode(i,i.uint32());break;case 4:o.status=nr.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(Bi||(Bi={}));var cl;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(cl||(cl={}));var b2;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(b2||(b2={}));var ul;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(ul||(ul={}));var nr;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(nr||(nr={}));var $5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})($5||($5={}));(function(r){r.codec=()=>ft($5)})(nr||(nr={}));var H5;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(H5||(H5={}));var yIe=C("libp2p:circuit-relay:utils");async function G5(r){let e=new TextEncoder().encode(r),t=await Ke.digest(e);return Ne.createV0(t)}function W5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var yZ=j(zk(),1);var CIe=C("libp2p:circuit-relay:advert-service");var oAe=C("libp2p:circuit-relay:server");var wZ=C("libp2p:stream:converter");function Y5(r){let{stream:e,remoteAddr:t}=r,{sink:n,source:i}=e,s=async function*(){for await(let c of i)c instanceof Uint8Array?yield c:yield*c}(),o={async sink(c){try{await n(c),a()}catch(u){u.type!=="aborted"&&wZ(u)}},source:s,remoteAddr:t,timeline:{open:Date.now(),close:void 0},async close(c){a(),await e.close(c)},abort(c){a(),e.abort(c)}};function a(){o.timeline.close==null&&(o.timeline.close=Date.now())}return o}var jo=C("libp2p:circuit-relay:discover-relays"),w2=class extends Ye{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Xo,{onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}}),this.discover().catch(e=>{jo.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){jo("searching peer store for relays");let e=await this.peerStore.all({filters:[t=>t.protocols.includes(Xo)],orders:[()=>Math.random()<.5?1:-1]});for(let t of e)jo("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});jo("found %d relay peers in peer store",e.length);try{jo("searching content routing for relays");let t=await G5(z5),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),jo("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}jo("found %d relay peers in content routing",n)}catch(t){jo.error("failed when finding relays on the network",t)}}};var Q5=C("libp2p:circuit-relay:transport:listener"),X5=class extends Ye{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new kr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){Q5("listen on %a",e);let t=e.getPeerId(),n;if(t!=null){let s=we(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=ge(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new w("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){Q5("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>ge(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);Q5("relay peer removed %p - had reservation",e,t),this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function Hk(r){return new X5(r)}var Gr=C("libp2p:circuit-relay:transport:reservation-store"),xZ=60*1e3*10,vZ=60*1e3*5,_Z=30*1e3,E2=class extends Ye{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;reservationCompletionTimeout;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new kr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new ru({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}async addRelay(e,t){if(this.peerId.equals(e)){Gr("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){Gr("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(e)){Gr("relay peer is already in the reservation queue");return}Gr("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(W5(n.reservation.expire)>xZ){Gr("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((l,f)=>(f.type==="discovered"&&l++,l),0)>=this.maxDiscoveredRelays){Gr("already have enough discovered relays");return}let i=AbortSignal.timeout(this.reservationCompletionTimeout),s=await this.connectionManager.openConnection(e,{signal:i});if(s.remoteAddr.protoNames().includes("p2p-circuit")){Gr("not creating reservation over relayed connection");return}let o=await this.#e(s,{signal:i});Gr("created reservation on relay peer %p",e);let a=W5(o.expire),c=Math.min(Math.max(a-vZ,_Z),Math.pow(2,31)-1),u=setTimeout(()=>{this.addRelay(e,t).catch(l=>{Gr.error("could not refresh reservation to relay %p",e,l)})},c);this.reservations.set(e,{timeout:u,reservation:o,type:t}),await this.peerStore.merge(e,{tags:{[Mk]:{value:1,ttl:a}}}),await this.transportManager.listen([ge(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){Gr.error("could not reserve slot on %p",e,n);let i=this.reservations.get(e);i!=null&&clearTimeout(i.timeout),this.reservations.delete(e)}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e,t){t.signal?.throwIfAborted(),Gr("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Xo),s=_r(n).pb(Gs);await s.write({type:Gs.Type.RESERVE},t);let o;try{o=await s.read(t)}catch(c){throw Gr.error("error parsing reserve message response from %p because",e.remotePeer,c),c}finally{await n.close()}if(o.status===nr.OK&&o.reservation!=null)return o.reservation;let a=`reservation failed with status ${o.status??"undefined"}`;throw Gr.error(a),new Error(a)}#t(e){let t=this.reservations.get(e);t!=null&&(Gr("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size{if(r.peer==null)return!1;try{r.peer.addrs.forEach(ge)}catch{return!1}return!0},j5={maxInboundStopStreams:vo,maxOutboundStopStreams:vo,stopTimeout:3e4},Z5=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;stopTimeout;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??j5.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??j5.maxOutboundStopStreams,this.stopTimeout=t.stopTimeout??j5.stopTimeout,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new w2(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{Or.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new E2(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{Or.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(y2,e=>{this.onStop(e).catch(t=>{Or.error("error while handling STOP protocol",t),e.stream.abort(t)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(y2),this.started=!1}[Ji]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw Or.error(p,e),new w(p,Y.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=ge(n[0]),s=ge(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw Or.error(p),new w(p,Y.ERR_RELAYED_DIAL)}let c=we(o),u=we(a),l=!1,h=this.connectionManager.getConnections(c)[0];h==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),h=await this.connectionManager.openConnection(c,t),l=!0);let d;try{return d=await h.newStream([Xo]),await this.connectV2({stream:d,connection:h,destinationPeer:u,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:l})}catch(p){throw Or.error(`Circuit relay dial to destination ${u.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),l&&await h.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=_r(e),u=c.pb(Gs);await u.write({type:Gs.Type.CONNECT,peer:{id:n.toBytes(),addrs:[ge(i).bytes]}});let l=await u.read();if(l.status!==nr.OK)throw new w(`failed to connect via relay with status ${l?.status?.toString()??"undefined"}`,Y.ERR_HOP_REQUEST_FAILED);let f=Y5({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return Or("new outbound transient connection %a",f.remoteAddr),await this.upgrader.upgradeOutbound(f,{transient:!0})}catch(c){throw Or.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return Hk({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Ai.matches(t))}async onStop({connection:e,stream:t}){let n=AbortSignal.timeout(this.stopTimeout),i=_r(t).pb(Bi),s=await i.read({signal:n});if(Or("new circuit relay v2 stop stream from %p with type %s",e.remotePeer,s.type),s?.type===void 0){Or.error("type was missing from circuit v2 stop protocol request from %s",e.remotePeer),await i.write({type:Bi.Type.STATUS,status:nr.MALFORMED_MESSAGE},{signal:n}),await t.close();return}if(s.type!==Bi.Type.CONNECT){Or.error("invalid stop connect request via peer %p",e.remotePeer),await i.write({type:Bi.Type.STATUS,status:nr.UNEXPECTED_MESSAGE},{signal:n}),await t.close();return}if(!SZ(s)){Or.error("invalid stop connect request via peer %p",e.remotePeer),await i.write({type:Bi.Type.STATUS,status:nr.MALFORMED_MESSAGE},{signal:n}),await t.close();return}let o=Ot(s.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){Or.error("connection gater denied inbound relayed connection from %p",e.remotePeer),await i.write({type:Bi.Type.STATUS,status:nr.PERMISSION_DENIED},{signal:n}),await t.close();return}Or.trace("sending success response to %p",e.remotePeer),await i.write({type:Bi.Type.STATUS,status:nr.OK},{signal:n});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],u=Y5({stream:i.unwrap().unwrap(),remoteAddr:a,localAddr:c});Or("new inbound transient connection %a",u.remoteAddr),await this.upgrader.upgradeInbound(u,{transient:!0}),Or("%s connection %a upgraded","inbound",u.remoteAddr)}};function J5(r={}){return e=>new Z5(e,r)}var RZ=r=>r.toString().split("/").slice(1),Ph=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Xt=r=>({match:e=>Ph(t=>t===r).match(e),pattern:r}),v2=()=>({match:r=>Ph(e=>typeof e=="string").match(r),pattern:"{string}"}),Gk=()=>({match:r=>Ph(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Li=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Re.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),x2=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{U2.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),as=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),cs=(...r)=>({match:e=>{let t;for(let n of r){let i=n.match(e);i!==!1&&(t==null||i.lengthe.pattern).join(", ")})`}),Wt=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function dr(...r){function e(i){let s=RZ(i);for(let o of r){let a=o.match(s);if(a===!1)return!1;s=a}return s}function t(i){return e(i)!==!1}function n(i){let s=e(i);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var t6=Wt(Xt("dns4"),v2()),r6=Wt(Xt("dns6"),v2()),n6=Wt(Xt("dnsaddr"),v2()),Wk=Wt(Xt("dns"),v2()),tTe=dr(t6),rTe=dr(r6),nTe=dr(n6),Yk=dr(cs(Wk,n6,t6,r6)),Qk=Wt(Xt("ip4"),Ph(Od)),Xk=Wt(Xt("ip6"),Ph(Bd)),jk=cs(Qk,Xk),_2=cs(jk,Wk,t6,r6,n6),iTe=dr(Qk),sTe=dr(Xk),Zk=dr(jk),S2=Wt(_2,Xt("tcp"),Gk()),kh=Wt(_2,Xt("udp"),Gk()),IZ=cs(S2,kh),oTe=dr(S2),aTe=dr(kh),i6=Wt(kh,Xt("quic")),R2=Wt(kh,Xt("quic-v1")),AZ=cs(i6,R2),cTe=dr(i6),uTe=dr(R2),e6=cs(_2,S2,kh,i6,R2),Jk=cs(Wt(e6,Xt("ws"),as(Li()))),lTe=dr(Jk),eN=cs(Wt(e6,Xt("wss"),as(Li())),Wt(e6,Xt("tls"),Xt("ws"),as(Li()))),fTe=dr(eN),tN=Wt(IZ,Xt("webrtc-direct"),x2(),as(x2()),as(Li())),hTe=dr(tN),rN=Wt(R2,Xt("webtransport"),x2(),x2(),as(Li())),dTe=dr(rN),s6=cs(Jk,eN,Wt(S2,as(Li())),Wt(AZ,as(Li())),Wt(_2,as(Li())),tN,rN,Li()),pTe=dr(s6),nN=Wt(s6,Xt("p2p-circuit"),Li()),iN=dr(nN),TZ=cs(Wt(nN,Xt("webrtc")),Wt(s6,Xt("webrtc"),as(Li())),Xt("webrtc")),mTe=dr(TZ);var sN=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},DZ=new WeakMap;function CZ({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:i}={})=>{if(i?.aborted)return Promise.reject(sN());let s,o,a,c=r??clearTimeout,u=()=>{c(s),a(sN())},l=()=>{i&&i.removeEventListener("abort",u)},f=new Promise((h,d)=>{o=()=>{l(),h(n)},a=d,s=(e??setTimeout)(o,t)});return i&&i.addEventListener("abort",u,{once:!0}),DZ.set(f,()=>{c(s),s=null,o()}),f}}var PZ=CZ(),oN=PZ;var Mi;(function(r){let e;(function(i){i.UNUSED="UNUSED",i.CONNECT="CONNECT",i.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.UNUSED=0]="UNUSED",i[i.CONNECT=100]="CONNECT",i[i.SYNC=300]="SYNC"})(t||(t={})),function(i){i.codec=()=>ft(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=me((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.observedAddresses!=null)for(let a of i.observedAddresses)s.uint32(18),s.bytes(a);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={observedAddresses:[]},a=s==null?i.len:i.pos+s;for(;i.pos>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.observedAddresses.push(i.bytes());break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>pe(i,r.codec()),r.decode=i=>de(i,r.codec())})(Mi||(Mi={}));var Rt=C("libp2p:dcutr"),aN=1024*4,cN=100,I2={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},A2=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;constructor(e,t){this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??I2.timeout,this.retries=t.retries??I2.retries,this.maxInboundStreams=t.maxInboundStreams??I2.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??I2.maxOutboundStreams}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(Nh,{onConnect:(e,t)=>{t.transient&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{Rt.error("error during outgoing DCUtR attempt",n)})}}),await this.registrar.handle(Nh,e=>{this.handleIncomingUpgrade(e.stream,e.connection).catch(t=>{Rt.error("error during incoming DCUtR attempt",t),e.stream.abort(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(Nh),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;nf.bytes)},i),Rt("B receiving connect from %p",e.remotePeer);let a=await s.read(i);if(a.type!==Mi.Type.CONNECT)throw Rt("A sent wrong message type"),new w("DCUtR message type was incorrect",Y.ERR_INVALID_MESSAGE);let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw Rt("A did not have any dialable multiaddrs"),new w("DCUtR connect message had no multiaddrs",Y.ERR_INVALID_MESSAGE);let u=Date.now()-o;Rt("A sending sync, rtt %dms",u),await s.write({type:Mi.Type.SYNC,observedAddresses:[]},i),Rt("A waiting for half RTT"),await oN(u/2),Rt("B dialing",c);let l=await this.connectionManager.openConnection(c,{signal:i.signal,priority:cN});Rt("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,l.remoteAddr),await e.close(i);break}catch(s){if(Rt.error("error while attempting DCUtR on attempt %d of %d",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(i)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(i=>{let s=i.multiaddr;return s.getPeerId()==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(i=>this.isPublicAndDialable(i));if(n.length>0){let i=AbortSignal.timeout(this.timeout);try{Rt("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:i,force:!0});if(s.transient)throw new Error("Could not open a new, non-transient, connection");return Rt("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close(),!0}catch(s){Rt.error("unilateral connection upgrade to %p on addresses %a failed",e.remotePeer,n,s)}}else Rt("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)};try{let i=_r(e,{maxDataLength:aN}).pb(Mi);Rt("A receiving connect");let s=await i.read(n);if(s.type!==Mi.Type.CONNECT)throw Rt("B sent wrong message type"),new w("DCUtR message type was incorrect",Y.ERR_INVALID_MESSAGE);if(s.observedAddresses.length===0)throw Rt("B sent no multiaddrs"),new w("DCUtR connect message had no multiaddrs",Y.ERR_INVALID_MESSAGE);let o=this.getDialableMultiaddrs(s.observedAddresses);if(o.length===0)throw Rt("B had no dialable multiaddrs"),new w("DCUtR connect message had no dialable multiaddrs",Y.ERR_INVALID_MESSAGE);if(Rt("A sending connect"),await i.write({type:Mi.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(u=>u.bytes)}),Rt("A receiving sync"),(await i.read(n)).type!==Mi.Type.SYNC)throw new w("DCUtR message type was incorrect",Y.ERR_INVALID_MESSAGE);Rt("A dialing",o);let c=await this.connectionManager.openConnection(o,{signal:n.signal,priority:cN,force:!0});Rt("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n)}catch(i){Rt.error("incoming DCUtR from %p failed",t.remotePeer,i),e.abort(i)}finally{await e.close(n)}}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let i=ge(n);if(!this.isPublicAndDialable(i))continue;t.push(i)}catch{}return t}isPublicAndDialable(e){if(iN.matches(e))return!1;if(Yk.matches(e))return!0;if(!Zk.matches(e)||this.transportManager.transportForMultiaddr(e)==null)return!1;let n=e.toOptions();return Jr(n.host)===!1}};var Nh="/libp2p/dcutr";function uN(r={}){return e=>new A2(e,r)}var lN="0.46.6";var o6=`js-libp2p/${lN}`;var fN="0.1.0",hN="id",dN="id/push",pN="1.0.0",mN="1.0.0";var c6=j(Xr(),1);var Zo;(function(r){let e;r.codec=()=>(e==null&&(e=me((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>pe(t,r.codec()),r.decode=t=>de(t,r.codec())})(Zo||(Zo={}));var Br=C("libp2p:identify"),a6=1024*8,On={protocolPrefix:"ipfs",agentVersion:o6,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0},T2=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??On.protocolPrefix}/${hN}/${pN}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??On.protocolPrefix}/${dN}/${mN}`,this.timeout=t.timeout??On.timeout,this.maxInboundStreams=t.maxInboundStreams??On.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??On.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??On.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??On.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??On.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??On.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??On.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??On.protocolPrefix}/${fN}`,agentVersion:t.agentVersion??On.agentVersion},(t.runOnConnectionOpen??On.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{Br.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{Br.error(i)})}),this.host.agentVersion===o6&&(zD||VD?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Fp||Kp||qD||$D)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:G(this.host.agentVersion),ProtocolVersion:G(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{Br.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{Br.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(l=>l.decapsulateCode(le("p2p").code)),n=new yn({peerId:this.peerId,multiaddrs:t}),i=await Gn.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=U(o.metadata.get("AgentVersion")??G(this.host.agentVersion)),c=U(o.metadata.get("ProtocolVersion")??G(this.host.protocolVersion)),u=e.map(async l=>{let f,h=AbortSignal.timeout(this.timeout);try{(0,c6.setMaxListeners)?.(1/0,h)}catch{}try{f=await l.newStream([this.identifyPushProtocolStr],{signal:h,runOnTransientConnection:this.runOnTransientConnection}),await _r(f,{maxDataLength:this.maxIdentifyMessageSize??a6}).pb(Zo).write({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c},{signal:h}),await f.close({signal:h})}catch(d){Br.error("could not push identify update to peer",d),f?.abort(d)}});await Promise.all(u)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==Y.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n;t.signal=t.signal??AbortSignal.timeout(this.timeout);try{n=await e.newStream([this.identifyProtocolStr],{...t,runOnTransientConnection:this.runOnTransientConnection});let s=await _r(n,{maxDataLength:this.maxIdentifyMessageSize??a6}).pb(Zo).read(t);return await n.close(t),s}catch(i){throw Br.error("error while reading identify message",i),n?.abort(i),i}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new w("public key was missing from identify message",Y.ERR_MISSING_PUBLIC_KEY);let a=await Zr(i);if(!e.remotePeer.equals(a))throw new w("identified peer does not match the expected peer",Y.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new w("identified peer is our own peer id?",Y.ERR_INVALID_PEER);let c=kZ(o);Br("identify completed for peer %p and protocols %o",a,s),Br("our observed address is %a",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(Br("storing our observed address %a",c),this.addressManager.addObservedAddr(c));let u=await this.#e(e.remotePeer,n),l={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(f=>ge(f)),observedAddr:n.observedAddr==null?void 0:ge(n.observedAddr),protocols:n.protocols,signedPeerRecord:u};return this.events.safeDispatchEvent("peer:identify",{detail:l}),l}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,c6.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(l=>l.decapsulateCode(le("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let l=new yn({peerId:this.peerId,multiaddrs:a});c=(await Gn.seal(l,this.peerId)).marshal().subarray()}await _r(n).pb(Zo).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(l=>l.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols},{signal:i}),await n.close({signal:i})}catch(s){Br.error("could not respond to identify request",s),n.abort(s)}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i={signal:AbortSignal.timeout(this.timeout)},o=await _r(n,{maxDataLength:this.maxIdentifyMessageSize??a6}).pb(Zo).read(i);await n.close(i),await this.#e(t.remotePeer,o)}catch(i){Br.error("received invalid message",i),n.abort(i);return}Br("handled push from %p",t.remotePeer)}async#e(e,t){if(Br("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(s=>({isCertified:!1,multiaddr:ge(s)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},i;if(t.signedPeerRecord!=null){Br("received signedPeerRecord in push from %p",e);let s=t.signedPeerRecord,o=await Gn.openAndCertify(s,yn.DOMAIN),a=yn.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let u=await Gn.createFromProtobuf(c.peerRecordEnvelope),l=yn.createFromProtobuf(u.payload);l.seqNumber>=a.seqNumber&&(Br("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,a.seqNumber),a=l,s=c.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(u=>({isCertified:!0,multiaddr:u})),i={seq:a.seqNumber,addresses:a.multiaddrs}}else Br("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",G(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",G(t.protocolVersion)),await this.peerStore.patch(e,n),i}};function kZ(r){if(r!=null&&r.length>0)try{return ge(r)}catch{}}function gN(r={}){return e=>new T2(e,r)}var yN={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function bN(){return{addresses:{listen:["/webrtc"]},transports:[pD(),dD(),eC(),jD(),J5({discoverRelays:1})],connectionEncryption:[mu()],streamMuxers:[cI(),bA()],peerDiscovery:[EI(yN)],contentRouters:[AI("https://cid.contact")],services:{identify:gN(),autoNAT:Lk(),pubsub:wR(),dcutr:uN(),dht:aA({clientMode:!0,validators:{ipns:kk},selectors:{ipns:Pk}})}}}async function wN(r,e){let t=bN();return e=e??{},NS({datastore:r,...t,...e,start:!1})}var u6="2.0.1",D2="helia";var NZ=C("helia");async function OZ(r={}){let e=r.datastore??new na,t=r.blockstore??new ml,n;BZ(r.libp2p)?n=r.libp2p:n=await wN(e,r.libp2p);let i=new q0({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await EN(i):i.libp2p.addEventListener("start",()=>{EN(i).catch(s=>{NZ.error("could not add Helia to agent version",s)})}),i}function BZ(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function EN(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(D2)?n=`${D2}/${u6} ${n.split(" ").slice(1).join(" ")}`:n=`${D2}/${u6} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return Bh(LZ);})(); /*! Bundled license information: @noble/hashes/esm/utils.js: (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/utils.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/modular.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/curve.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/edwards.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/montgomery.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/ed25519.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/weierstrass.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/_shortw_utils.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/secp256k1.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/ciphers/esm/utils.js: (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *) @libp2p/webtransport/dist/src/index.js: (*! TODO unclear how to add backpressure here? *) @noble/ed25519/lib/esm/index.js: (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *) @noble/secp256k1/lib/esm/index.js: (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *) */ return Helia}));