@libp2p/simple-metrics 2.0.5 → 2.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +8 -3
- package/dist/index.min.js.map +3 -3
- package/package.json +2 -2
package/dist/index.min.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PSimpleMetrics = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PSimpleMetrics=(()=>{var
|
|
3
|
-
`)};function xe(t,e){return t.mean>e.mean?1:t.mean<e.mean?-1:0}function it(t,e){return t.mean_cumn-e.mean_cumn}d.prototype.push=function(t,e){e=e||1,t=Array.isArray(t)?t:[t];for(var r=0;r<t.length;r++)this._digest(t[r],e)};d.prototype.push_centroid=function(t){t=Array.isArray(t)?t:[t];for(var e=0;e<t.length;e++)this._digest(t[e].mean,t[e].n)};d.prototype._cumulate=function(t){if(!(this.n===this.last_cumulate||!t&&this.CX&&this.CX>this.n/this.last_cumulate)){var e=0;this.centroids.each(function(r){r.mean_cumn=e+r.n/2,e=r.cumn=e+r.n}),this.n=this.last_cumulate=e}};d.prototype.find_nearest=function(t){if(this.size()===0)return null;var e=this.centroids.lowerBound({mean:t}),r=e.data()===null?e.prev():e.data();if(r.mean===t||this.discrete)return r;var n=e.prev();return n&&Math.abs(n.mean-t)<Math.abs(r.mean-t)?n:r};d.prototype._new_centroid=function(t,e,r){var n={mean:t,n:e,cumn:r};return this.centroids.insert(n),this.n+=e,n};d.prototype._addweight=function(t,e,r){e!==t.mean&&(t.mean+=r*(e-t.mean)/(t.n+r)),t.cumn+=r,t.mean_cumn+=r/2,t.n+=r,this.n+=r};d.prototype._digest=function(t,e){var r=this.centroids.min(),n=this.centroids.max(),i=this.find_nearest(t);if(i&&i.mean===t)this._addweight(i,t,e);else if(i===r)this._new_centroid(t,e,0);else if(i===n)this._new_centroid(t,e,this.n);else if(this.discrete)this._new_centroid(t,e,i.cumn);else{var o=i.mean_cumn/this.n,a=Math.floor(4*this.n*this.delta*o*(1-o));a-i.n>=e?this._addweight(i,t,e):this._new_centroid(t,e,i.cumn)}this._cumulate(!1),!this.discrete&&this.K&&this.size()>this.K/this.delta&&this.compress()};d.prototype.bound_mean=function(t){var e=this.centroids.upperBound({mean:t}),r=e.prev(),n=r.mean===t?r:e.next();return[r,n]};d.prototype.p_rank=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._p_rank,this);return Array.isArray(t)?r:r[0]};d.prototype._p_rank=function(t){if(this.size()!==0){{if(t<this.centroids.min().mean)return 0;if(t>this.centroids.max().mean)return 1}this._cumulate(!0);var e=this.bound_mean(t),r=e[0],n=e[1];if(this.discrete)return r.cumn/this.n;var i=r.mean_cumn;return r!==n&&(i+=(t-r.mean)*(n.mean_cumn-r.mean_cumn)/(n.mean-r.mean)),i/this.n}};d.prototype.bound_mean_cumn=function(t){this.centroids._comparator=it;var e=this.centroids.upperBound({mean_cumn:t});this.centroids._comparator=xe;var r=e.prev(),n=r&&r.mean_cumn===t?r:e.next();return[r,n]};d.prototype.percentile=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._percentile,this);return Array.isArray(t)?r:r[0]};d.prototype._percentile=function(t){if(this.size()!==0){this._cumulate(!0);var e=this.n*t,r=this.bound_mean_cumn(e),n=r[0],i=r[1];return i===n||n===null||i===null?(n||i).mean:this.discrete?e<=n.cumn?n.mean:i.mean:n.mean+(e-n.mean_cumn)*(i.mean-n.mean)/(i.mean_cumn-n.mean_cumn)}};function st(t){var e=Math.floor(Math.random()*t.length);return t.splice(e,1)[0]}d.prototype.compress=function(){if(!this.compressing){var t=this.toArray();for(this.reset(),this.compressing=!0;t.length>0;)this.push_centroid(st(t));this._cumulate(!0),this.compressing=!1}};function V(t){this.config=t||{},this.mode=this.config.mode||"auto",d.call(this,this.mode==="cont"?t.delta:!1),this.digest_ratio=this.config.ratio||.9,this.digest_thresh=this.config.thresh||1e3,this.n_unique=0}V.prototype=Object.create(d.prototype);V.prototype.constructor=V;V.prototype.push=function(t){d.prototype.push.call(this,t),this.check_continuous()};V.prototype._new_centroid=function(t,e,r){this.n_unique+=1,d.prototype._new_centroid.call(this,t,e,r)};V.prototype._addweight=function(t,e,r){t.n===1&&(this.n_unique-=1),d.prototype._addweight.call(this,t,e,r)};V.prototype.check_continuous=function(){return this.mode!=="auto"||this.size()<this.digest_thresh?!1:this.n_unique/this.size()>this.digest_ratio?(this.mode="cont",this.discrete=!1,this.delta=this.config.delta||.01,this.compress(),!0):!1};Fe.exports={TDigest:d,Digest:V}});var ut={};Se(ut,{simpleMetrics:()=>at});var se=Symbol.for("@libp2p/service-capabilities"),lt=Symbol.for("@libp2p/service-dependencies");var Nt=new Uint8Array(0);function oe(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function De(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");r[a]=i}var c=t.length,l=t.charAt(0),y=Math.log(c)/Math.log(256),s=Math.log(256)/Math.log(c);function u(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,m=0,g=0,_=h.length;g!==_&&h[g]===0;)g++,p++;for(var x=(_-g)*s+1>>>0,b=new Uint8Array(x);g!==_;){for(var E=h[g],F=0,C=x-1;(E!==0||F<m)&&C!==-1;C--,F++)E+=256*b[C]>>>0,b[C]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");m=F,g++}for(var A=x-m;A!==x&&b[A]===0;)A++;for(var S=l.repeat(p);A<x;++A)S+=t.charAt(b[A]);return S}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var m=0,g=0;h[p]===l;)m++,p++;for(var _=(h.length-p)*y+1>>>0,x=new Uint8Array(_);h[p];){var b=r[h.charCodeAt(p)];if(b===255)return;for(var E=0,F=_-1;(b!==0||E<g)&&F!==-1;F--,E++)b+=c*x[F]>>>0,x[F]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");g=E,p++}if(h[p]!==" "){for(var C=_-g;C!==_&&x[C]===0;)C++;for(var A=new Uint8Array(m+(_-C)),S=m;C!==_;)A[S++]=x[C++];return A}}}function $(h){var p=f(h);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:$}}var Ne=De,je=Ne,ae=je;var X=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},G=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,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 ue(this,e)}},K=class{decoders;constructor(e){this.decoders=e}or(e){return ue(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ue(t,e){return new K({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Z=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new X(e,r,n),this.decoder=new G(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ce({name:t,prefix:e,encode:r,decode:n}){return new Z(t,e,r,n)}function W({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=ae(r,t);return ce({prefix:e,name:t,encode:n,decode:o=>oe(i(o))})}function Te(t,e,r,n){let i=t.length;for(;t[i-1]==="=";)--i;let o=new Uint8Array(i*r/8|0),a=0,c=0,l=0;for(let y=0;y<i;++y){let s=e[t[y]];if(s===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|s,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return o}function qe(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",a=0,c=0;for(let l=0;l<t.length;++l)for(c=c<<8|t[l],a+=8;a>r;)a-=r,o+=e[i&c>>a];if(a!==0&&(o+=e[i&c<<r-a]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function Be(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function w({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let i=Be(n);return ce({prefix:e,name:t,encode(o){return qe(o,n,r)},decode(o){return Te(o,i,r,t)}})}var le=w({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Pt=w({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Rt=w({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Jt=w({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qt=w({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Xt=w({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Gt=w({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Kt=w({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zt=w({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var he=W({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ht=W({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fe=w({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rr=w({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nr=w({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ir=w({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Ie(t,e){if(typeof t=="string")return Le(t);if(typeof t=="number")return Je(t,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(t)}`)}var q=Ie;function Le(t){if(typeof t!="string"||t.length===0||t.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(t)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(t);if(!e?.groups)return NaN;let{value:r,unit:n="ms"}=e.groups,i=parseFloat(r),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(t)}`)}}function Pe(t){let e=Math.abs(t);return e>=315576e5?`${Math.round(t/315576e5)}y`:e>=26298e5?`${Math.round(t/26298e5)}mo`:e>=6048e5?`${Math.round(t/6048e5)}w`:e>=864e5?`${Math.round(t/864e5)}d`:e>=36e5?`${Math.round(t/36e5)}h`:e>=6e4?`${Math.round(t/6e4)}m`:e>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function Re(t){let e=Math.abs(t);return e>=315576e5?z(t,e,315576e5,"year"):e>=26298e5?z(t,e,26298e5,"month"):e>=6048e5?z(t,e,6048e5,"week"):e>=864e5?z(t,e,864e5,"day"):e>=36e5?z(t,e,36e5,"hour"):e>=6e4?z(t,e,6e4,"minute"):e>=1e3?z(t,e,1e3,"second"):`${t} ms`}function Je(t,e){if(typeof t!="number"||!Number.isFinite(t))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Re(t):Pe(t)}function z(t,e,r,n){let i=e>=r*1.5;return`${Math.round(t/r)} ${n}${i?"s":""}`}function Y(t){r.debug=r,r.default=r,r.coerce=l,r.disable=o,r.enable=i,r.enabled=a,r.humanize=q,r.destroy=y,Object.keys(t).forEach(s=>{r[s]=t[s]}),r.names=[],r.skips=[],r.formatters={};function e(s){let u=0;for(let f=0;f<s.length;f++)u=(u<<5)-u+s.charCodeAt(f),u|=0;return r.colors[Math.abs(u)%r.colors.length]}r.selectColor=e;function r(s){let u,f=null,$,h;function p(...m){if(!p.enabled)return;let g=p,_=Number(new Date),x=_-(u||_);g.diff=x,g.prev=u,g.curr=_,u=_,m[0]=r.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let b=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(F,C)=>{if(F==="%%")return"%";b++;let A=r.formatters[C];if(typeof A=="function"){let S=m[b];F=A.call(g,S),m.splice(b,1),b--}return F}),r.formatArgs.call(g,m),(g.log||r.log).apply(g,m)}return p.namespace=s,p.useColors=r.useColors(),p.color=r.selectColor(s),p.extend=n,p.destroy=r.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:($!==r.namespaces&&($=r.namespaces,h=r.enabled(s)),h),set:m=>{f=m}}),typeof r.init=="function"&&r.init(p),p}function n(s,u){let f=r(this.namespace+(typeof u>"u"?":":u)+s);return f.log=this.log,f}function i(s){r.save(s),r.namespaces=s,r.names=[],r.skips=[];let u,f=(typeof s=="string"?s:"").split(/[\s,]+/),$=f.length;for(u=0;u<$;u++)f[u]&&(s=f[u].replace(/\*/g,".*?"),s[0]==="-"?r.skips.push(new RegExp("^"+s.substr(1)+"$")):r.names.push(new RegExp("^"+s+"$")))}function o(){let s=[...r.names.map(c),...r.skips.map(c).map(u=>"-"+u)].join(",");return r.enable(""),s}function a(s){if(s[s.length-1]==="*")return!0;let u,f;for(u=0,f=r.skips.length;u<f;u++)if(r.skips[u].test(s))return!1;for(u=0,f=r.names.length;u<f;u++)if(r.names[u].test(s))return!0;return!1}function c(s){return s.toString().substring(2,s.toString().length-2).replace(/\.\*\?$/,"*")}function l(s){return s instanceof Error?s.stack??s.message:s}function y(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.setupFormatters(r.formatters),r.enable(r.load()),r}var B=Ye(),Qe=["#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 Xe(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Ge(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+q(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}var Ke=console.debug??console.log??(()=>{});function Ze(t){try{t?B?.setItem("debug",t):B?.removeItem("debug")}catch{}}function We(){let t;try{t=B?.getItem("debug")}catch{}return!t&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(t=globalThis.process.env.DEBUG),t}function Ye(){try{return localStorage}catch{}}function He(t){t.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}}var pe=Y({formatArgs:Ge,save:Ze,load:We,useColors:Xe,setupFormatters:He,colors:Qe,storage:B,log:Ke});var v=pe;v.formatters.b=t=>t==null?"undefined":he.baseEncode(t);v.formatters.t=t=>t==null?"undefined":le.baseEncode(t);v.formatters.m=t=>t==null?"undefined":fe.baseEncode(t);v.formatters.p=t=>t==null?"undefined":t.toString();v.formatters.c=t=>t==null?"undefined":t.toString();v.formatters.k=t=>t==null?"undefined":t.toString();v.formatters.a=t=>t==null?"undefined":t.toString();v.formatters.e=t=>{if(t==null)return"undefined";let e=de(t.message),r=de(t.stack);return e!=null&&r!=null?r.includes(e)?r:`${e}
|
|
4
|
-
${r}`:r??e??t.toString()}
|
|
2
|
+
"use strict";var Libp2PSimpleMetrics=(()=>{var Me=Object.create;var T=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ue=(t,e)=>{for(var r in e)T(t,r,{get:e[r],enumerable:!0})},se=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ve(e))!Se.call(t,i)&&i!==r&&T(t,i,{get:()=>e[i],enumerable:!(n=$e(e,i))||n.enumerable});return t};var Oe=(t,e,r)=>(r=t!=null?Me(ze(t)):{},se(e||!t||!t.__esModule?T(r,"default",{value:t,enumerable:!0}):r,t)),De=t=>se(T({},"__esModule",{value:!0}),t);var te=D((yr,ge)=>{function M(){}M.prototype.clear=function(){this._root=null,this.size=0};M.prototype.find=function(t){for(var e=this._root;e!==null;){var r=this._comparator(t,e.data);if(r===0)return e.data;e=e.get_child(r>0)}return null};M.prototype.findIter=function(t){for(var e=this._root,r=this.iterator();e!==null;){var n=this._comparator(t,e.data);if(n===0)return r._cursor=e,r;r._ancestors.push(e),e=e.get_child(n>0)}return null};M.prototype.lowerBound=function(t){for(var e=this._root,r=this.iterator(),n=this._comparator;e!==null;){var i=n(t,e.data);if(i===0)return r._cursor=e,r;r._ancestors.push(e),e=e.get_child(i>0)}for(var o=r._ancestors.length-1;o>=0;--o)if(e=r._ancestors[o],n(t,e.data)<0)return r._cursor=e,r._ancestors.length=o,r;return r._ancestors.length=0,r};M.prototype.upperBound=function(t){for(var e=this.lowerBound(t),r=this._comparator;e.data()!==null&&r(e.data(),t)===0;)e.next();return e};M.prototype.min=function(){var t=this._root;if(t===null)return null;for(;t.left!==null;)t=t.left;return t.data};M.prototype.max=function(){var t=this._root;if(t===null)return null;for(;t.right!==null;)t=t.right;return t.data};M.prototype.iterator=function(){return new U(this)};M.prototype.each=function(t){for(var e=this.iterator(),r;(r=e.next())!==null;)if(t(r)===!1)return};M.prototype.reach=function(t){for(var e=this.iterator(),r;(r=e.prev())!==null;)if(t(r)===!1)return};function U(t){this._tree=t,this._ancestors=[],this._cursor=null}U.prototype.data=function(){return this._cursor!==null?this._cursor.data:null};U.prototype.next=function(){if(this._cursor===null){var t=this._tree._root;t!==null&&this._minNode(t)}else if(this._cursor.right===null){var e;do if(e=this._cursor,this._ancestors.length)this._cursor=this._ancestors.pop();else{this._cursor=null;break}while(this._cursor.right===e)}else this._ancestors.push(this._cursor),this._minNode(this._cursor.right);return this._cursor!==null?this._cursor.data:null};U.prototype.prev=function(){if(this._cursor===null){var t=this._tree._root;t!==null&&this._maxNode(t)}else if(this._cursor.left===null){var e;do if(e=this._cursor,this._ancestors.length)this._cursor=this._ancestors.pop();else{this._cursor=null;break}while(this._cursor.left===e)}else this._ancestors.push(this._cursor),this._maxNode(this._cursor.left);return this._cursor!==null?this._cursor.data:null};U.prototype._minNode=function(t){for(;t.left!==null;)this._ancestors.push(t),t=t.left;this._cursor=t};U.prototype._maxNode=function(t){for(;t.right!==null;)this._ancestors.push(t),t=t.right;this._cursor=t};ge.exports=M});var we=D((Cr,_e)=>{var nt=te();function O(t){this.data=t,this.left=null,this.right=null,this.red=!0}O.prototype.get_child=function(t){return t?this.right:this.left};O.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function I(t){this._root=null,this._comparator=t,this.size=0}I.prototype=new nt;I.prototype.insert=function(t){var e=!1;if(this._root===null)this._root=new O(t),e=!0,this.size++;else{var r=new O(void 0),n=0,i=0,o=null,a=r,c=null,l=this._root;for(a.right=this._root;;){if(l===null?(l=new O(t),c.set_child(n,l),e=!0,this.size++):k(l.left)&&k(l.right)&&(l.red=!0,l.left.red=!1,l.right.red=!1),k(l)&&k(c)){var x=a.right===o;l===c.get_child(i)?a.set_child(x,N(o,!i)):a.set_child(x,be(o,!i))}var s=this._comparator(l.data,t);if(s===0)break;i=n,n=s<0,o!==null&&(a=o),o=c,c=l,l=l.get_child(n)}this._root=r.right}return this._root.red=!1,e};I.prototype.remove=function(t){if(this._root===null)return!1;var e=new O(void 0),r=e;r.right=this._root;for(var n=null,i=null,o=null,a=1;r.get_child(a)!==null;){var c=a;i=n,n=r,r=r.get_child(a);var l=this._comparator(t,r.data);if(a=l>0,l===0&&(o=r),!k(r)&&!k(r.get_child(a))){if(k(r.get_child(!a))){var x=N(r,a);n.set_child(c,x),n=x}else if(!k(r.get_child(!a))){var s=n.get_child(!c);if(s!==null)if(!k(s.get_child(!c))&&!k(s.get_child(c)))n.red=!1,s.red=!0,r.red=!0;else{var u=i.right===n;k(s.get_child(c))?i.set_child(u,be(n,c)):k(s.get_child(!c))&&i.set_child(u,N(n,c));var f=i.get_child(u);f.red=!0,r.red=!0,f.left.red=!1,f.right.red=!1}}}}return o!==null&&(o.data=r.data,n.set_child(n.right===r,r.get_child(r.left===null)),this.size--),this._root=e.right,this._root!==null&&(this._root.red=!1),o!==null};function k(t){return t!==null&&t.red}function N(t,e){var r=t.get_child(!e);return t.set_child(!e,r.get_child(e)),r.set_child(e,t),t.red=!0,r.red=!1,r}function be(t,e){return t.set_child(!e,N(t.get_child(!e),!e)),N(t,e)}_e.exports=I});var ye=D((xr,ve)=>{var it=te();function j(t){this.data=t,this.left=null,this.right=null}j.prototype.get_child=function(t){return t?this.right:this.left};j.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function L(t){this._root=null,this._comparator=t,this.size=0}L.prototype=new it;L.prototype.insert=function(t){if(this._root===null)return this._root=new j(t),this.size++,!0;for(var e=0,r=null,n=this._root;;){if(n===null)return n=new j(t),r.set_child(e,n),ret=!0,this.size++,!0;if(this._comparator(n.data,t)===0)return!1;e=this._comparator(n.data,t)<0,r=n,n=n.get_child(e)}};L.prototype.remove=function(t){if(this._root===null)return!1;var e=new j(void 0),r=e;r.right=this._root;for(var n=null,i=null,o=1;r.get_child(o)!==null;){n=r,r=r.get_child(o);var a=this._comparator(t,r.data);o=a>0,a===0&&(i=r)}return i!==null?(i.data=r.data,n.set_child(n.right===r,r.get_child(r.left===null)),this._root=e.right,this.size--,!0):!1};ve.exports=L});var xe=D((Fr,Ce)=>{Ce.exports={RBTree:we(),BinTree:ye()}});var Ee=D((Ar,Ae)=>{var st=xe().RBTree;function d(t,e,r){this.discrete=t===!1,this.delta=t||.01,this.K=e===void 0?25:e,this.CX=r===void 0?1.1:r,this.centroids=new st(Fe),this.nreset=0,this.reset()}d.prototype.reset=function(){this.centroids.clear(),this.n=0,this.nreset+=1,this.last_cumulate=0};d.prototype.size=function(){return this.centroids.size};d.prototype.toArray=function(t){var e=[];return t?(this._cumulate(!0),this.centroids.each(function(r){e.push(r)})):this.centroids.each(function(r){e.push({mean:r.mean,n:r.n})}),e};d.prototype.summary=function(){var t=this.discrete?"exact ":"approximating ",e=[t+this.n+" samples using "+this.size()+" centroids","min = "+this.percentile(0),"Q1 = "+this.percentile(.25),"Q2 = "+this.percentile(.5),"Q3 = "+this.percentile(.75),"max = "+this.percentile(1)];return e.join(`
|
|
3
|
+
`)};function Fe(t,e){return t.mean>e.mean?1:t.mean<e.mean?-1:0}function ot(t,e){return t.mean_cumn-e.mean_cumn}d.prototype.push=function(t,e){e=e||1,t=Array.isArray(t)?t:[t];for(var r=0;r<t.length;r++)this._digest(t[r],e)};d.prototype.push_centroid=function(t){t=Array.isArray(t)?t:[t];for(var e=0;e<t.length;e++)this._digest(t[e].mean,t[e].n)};d.prototype._cumulate=function(t){if(!(this.n===this.last_cumulate||!t&&this.CX&&this.CX>this.n/this.last_cumulate)){var e=0;this.centroids.each(function(r){r.mean_cumn=e+r.n/2,e=r.cumn=e+r.n}),this.n=this.last_cumulate=e}};d.prototype.find_nearest=function(t){if(this.size()===0)return null;var e=this.centroids.lowerBound({mean:t}),r=e.data()===null?e.prev():e.data();if(r.mean===t||this.discrete)return r;var n=e.prev();return n&&Math.abs(n.mean-t)<Math.abs(r.mean-t)?n:r};d.prototype._new_centroid=function(t,e,r){var n={mean:t,n:e,cumn:r};return this.centroids.insert(n),this.n+=e,n};d.prototype._addweight=function(t,e,r){e!==t.mean&&(t.mean+=r*(e-t.mean)/(t.n+r)),t.cumn+=r,t.mean_cumn+=r/2,t.n+=r,this.n+=r};d.prototype._digest=function(t,e){var r=this.centroids.min(),n=this.centroids.max(),i=this.find_nearest(t);if(i&&i.mean===t)this._addweight(i,t,e);else if(i===r)this._new_centroid(t,e,0);else if(i===n)this._new_centroid(t,e,this.n);else if(this.discrete)this._new_centroid(t,e,i.cumn);else{var o=i.mean_cumn/this.n,a=Math.floor(4*this.n*this.delta*o*(1-o));a-i.n>=e?this._addweight(i,t,e):this._new_centroid(t,e,i.cumn)}this._cumulate(!1),!this.discrete&&this.K&&this.size()>this.K/this.delta&&this.compress()};d.prototype.bound_mean=function(t){var e=this.centroids.upperBound({mean:t}),r=e.prev(),n=r.mean===t?r:e.next();return[r,n]};d.prototype.p_rank=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._p_rank,this);return Array.isArray(t)?r:r[0]};d.prototype._p_rank=function(t){if(this.size()!==0){{if(t<this.centroids.min().mean)return 0;if(t>this.centroids.max().mean)return 1}this._cumulate(!0);var e=this.bound_mean(t),r=e[0],n=e[1];if(this.discrete)return r.cumn/this.n;var i=r.mean_cumn;return r!==n&&(i+=(t-r.mean)*(n.mean_cumn-r.mean_cumn)/(n.mean-r.mean)),i/this.n}};d.prototype.bound_mean_cumn=function(t){this.centroids._comparator=ot;var e=this.centroids.upperBound({mean_cumn:t});this.centroids._comparator=Fe;var r=e.prev(),n=r&&r.mean_cumn===t?r:e.next();return[r,n]};d.prototype.percentile=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._percentile,this);return Array.isArray(t)?r:r[0]};d.prototype._percentile=function(t){if(this.size()!==0){this._cumulate(!0);var e=this.n*t,r=this.bound_mean_cumn(e),n=r[0],i=r[1];return i===n||n===null||i===null?(n||i).mean:this.discrete?e<=n.cumn?n.mean:i.mean:n.mean+(e-n.mean_cumn)*(i.mean-n.mean)/(i.mean_cumn-n.mean_cumn)}};function at(t){var e=Math.floor(Math.random()*t.length);return t.splice(e,1)[0]}d.prototype.compress=function(){if(!this.compressing){var t=this.toArray();for(this.reset(),this.compressing=!0;t.length>0;)this.push_centroid(at(t));this._cumulate(!0),this.compressing=!1}};function $(t){this.config=t||{},this.mode=this.config.mode||"auto",d.call(this,this.mode==="cont"?t.delta:!1),this.digest_ratio=this.config.ratio||.9,this.digest_thresh=this.config.thresh||1e3,this.n_unique=0}$.prototype=Object.create(d.prototype);$.prototype.constructor=$;$.prototype.push=function(t){d.prototype.push.call(this,t),this.check_continuous()};$.prototype._new_centroid=function(t,e,r){this.n_unique+=1,d.prototype._new_centroid.call(this,t,e,r)};$.prototype._addweight=function(t,e,r){t.n===1&&(this.n_unique-=1),d.prototype._addweight.call(this,t,e,r)};$.prototype.check_continuous=function(){return this.mode!=="auto"||this.size()<this.digest_thresh?!1:this.n_unique/this.size()>this.digest_ratio?(this.mode="cont",this.discrete=!1,this.delta=this.config.delta||.01,this.compress(),!0):!1};Ae.exports={TDigest:d,Digest:$}});var lt={};Ue(lt,{simpleMetrics:()=>ct});var oe=Symbol.for("@libp2p/service-capabilities"),ft=Symbol.for("@libp2p/service-dependencies");var Tt=new Uint8Array(0);function ae(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Ne(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");r[a]=i}var c=t.length,l=t.charAt(0),x=Math.log(c)/Math.log(256),s=Math.log(256)/Math.log(c);function u(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var b=0,m=0,p=0,g=h.length;p!==g&&h[p]===0;)p++,b++;for(var _=(g-p)*s+1>>>0,y=new Uint8Array(_);p!==g;){for(var w=h[p],F=0,A=_-1;(w!==0||F<m)&&A!==-1;A--,F++)w+=256*y[A]>>>0,y[A]=w%c>>>0,w=w/c>>>0;if(w!==0)throw new Error("Non-zero carry");m=F,p++}for(var E=_-m;E!==_&&y[E]===0;)E++;for(var S=l.repeat(b);E<_;++E)S+=t.charAt(y[E]);return S}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var b=0;if(h[b]!==" "){for(var m=0,p=0;h[b]===l;)m++,b++;for(var g=(h.length-b)*x+1>>>0,_=new Uint8Array(g);h[b];){var y=r[h.charCodeAt(b)];if(y===255)return;for(var w=0,F=g-1;(y!==0||w<p)&&F!==-1;F--,w++)y+=c*_[F]>>>0,_[F]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");p=w,b++}if(h[b]!==" "){for(var A=g-p;A!==g&&_[A]===0;)A++;for(var E=new Uint8Array(m+(g-A)),S=m;A!==g;)E[S++]=_[A++];return E}}}function V(h){var b=f(h);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:V}}var je=Ne,Te=je,ue=Te;var X=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},G=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,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 ce(this,e)}},K=class{decoders;constructor(e){this.decoders=e}or(e){return ce(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ce(t,e){return new K({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Z=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new X(e,r,n),this.decoder=new G(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function le({name:t,prefix:e,encode:r,decode:n}){return new Z(t,e,r,n)}function W({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=ue(r,t);return le({prefix:e,name:t,encode:n,decode:o=>ae(i(o))})}function qe(t,e,r,n){let i=t.length;for(;t[i-1]==="=";)--i;let o=new Uint8Array(i*r/8|0),a=0,c=0,l=0;for(let x=0;x<i;++x){let s=e[t[x]];if(s===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|s,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return o}function Be(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",a=0,c=0;for(let l=0;l<t.length;++l)for(c=c<<8|t[l],a+=8;a>r;)a-=r,o+=e[i&c>>a];if(a!==0&&(o+=e[i&c<<r-a]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function Ie(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function v({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let i=Ie(n);return le({prefix:e,name:t,encode(o){return Be(o,n,r)},decode(o){return qe(o,i,r,t)}})}var he=v({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jt=v({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qt=v({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xt=v({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gt=v({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kt=v({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zt=v({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wt=v({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yt=v({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fe=W({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tr=W({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pe=v({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ir=v({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sr=v({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),or=v({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Le(t,e){if(typeof t=="string")return Pe(t);if(typeof t=="number")return Qe(t,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(t)}`)}var q=Le;function Pe(t){if(typeof t!="string"||t.length===0||t.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(t)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(t);if(!e?.groups)return NaN;let{value:r,unit:n="ms"}=e.groups,i=parseFloat(r),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(t)}`)}}function Re(t){let e=Math.abs(t);return e>=315576e5?`${Math.round(t/315576e5)}y`:e>=26298e5?`${Math.round(t/26298e5)}mo`:e>=6048e5?`${Math.round(t/6048e5)}w`:e>=864e5?`${Math.round(t/864e5)}d`:e>=36e5?`${Math.round(t/36e5)}h`:e>=6e4?`${Math.round(t/6e4)}m`:e>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function Je(t){let e=Math.abs(t);return e>=315576e5?z(t,e,315576e5,"year"):e>=26298e5?z(t,e,26298e5,"month"):e>=6048e5?z(t,e,6048e5,"week"):e>=864e5?z(t,e,864e5,"day"):e>=36e5?z(t,e,36e5,"hour"):e>=6e4?z(t,e,6e4,"minute"):e>=1e3?z(t,e,1e3,"second"):`${t} ms`}function Qe(t,e){if(typeof t!="number"||!Number.isFinite(t))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Je(t):Re(t)}function z(t,e,r,n){let i=e>=r*1.5;return`${Math.round(t/r)} ${n}${i?"s":""}`}function Y(t){r.debug=r,r.default=r,r.coerce=l,r.disable=o,r.enable=i,r.enabled=a,r.humanize=q,r.destroy=x,Object.keys(t).forEach(s=>{r[s]=t[s]}),r.names=[],r.skips=[],r.formatters={};function e(s){let u=0;for(let f=0;f<s.length;f++)u=(u<<5)-u+s.charCodeAt(f),u|=0;return r.colors[Math.abs(u)%r.colors.length]}r.selectColor=e;function r(s,u){let f,V=null,h,b;function m(...p){if(!m.enabled)return;let g=m,_=Number(new Date),y=_-(f||_);g.diff=y,g.prev=f,g.curr=_,f=_,p[0]=r.coerce(p[0]),typeof p[0]!="string"&&p.unshift("%O");let w=0;p[0]=p[0].replace(/%([a-zA-Z%])/g,(F,A)=>{if(F==="%%")return"%";w++;let E=r.formatters[A];if(typeof E=="function"){let S=p[w];F=E.call(g,S),p.splice(w,1),w--}return F}),r.formatArgs.call(g,p),u?.onLog!=null?u.onLog(...p):(g.log||r.log).apply(g,p)}return m.namespace=s,m.useColors=r.useColors(),m.color=r.selectColor(s),m.extend=n,m.destroy=r.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>V!==null?V:(h!==r.namespaces&&(h=r.namespaces,b=r.enabled(s)),b),set:p=>{V=p}}),typeof r.init=="function"&&r.init(m),m}function n(s,u){let f=r(this.namespace+(typeof u>"u"?":":u)+s);return f.log=this.log,f}function i(s){r.save(s),r.namespaces=s,r.names=[],r.skips=[];let u,f=(typeof s=="string"?s:"").split(/[\s,]+/),V=f.length;for(u=0;u<V;u++)f[u]&&(s=f[u].replace(/\*/g,".*?"),s[0]==="-"?r.skips.push(new RegExp("^"+s.substr(1)+"$")):r.names.push(new RegExp("^"+s+"$")))}function o(){let s=[...r.names.map(c),...r.skips.map(c).map(u=>"-"+u)].join(",");return r.enable(""),s}function a(s){if(s[s.length-1]==="*")return!0;let u,f;for(u=0,f=r.skips.length;u<f;u++)if(r.skips[u].test(s))return!1;for(u=0,f=r.names.length;u<f;u++)if(r.names[u].test(s))return!0;return!1}function c(s){return s.toString().substring(2,s.toString().length-2).replace(/\.\*\?$/,"*")}function l(s){return s instanceof Error?s.stack??s.message:s}function x(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.setupFormatters(r.formatters),r.enable(r.load()),r}var B=He(),Xe=["#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 Ge(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Ke(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+q(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}var Ze=console.debug??console.log??(()=>{});function We(t){try{t?B?.setItem("debug",t):B?.removeItem("debug")}catch{}}function Ye(){let t;try{t=B?.getItem("debug")}catch{}return!t&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(t=globalThis.process.env.DEBUG),t}function He(){try{return localStorage}catch{}}function et(t){t.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}}var de=Y({formatArgs:Ke,save:We,load:Ye,useColors:Ge,setupFormatters:et,colors:Xe,storage:B,log:Ze});var C=de;C.formatters.b=t=>t==null?"undefined":fe.baseEncode(t);C.formatters.t=t=>t==null?"undefined":he.baseEncode(t);C.formatters.m=t=>t==null?"undefined":pe.baseEncode(t);C.formatters.p=t=>t==null?"undefined":t.toString();C.formatters.c=t=>t==null?"undefined":t.toString();C.formatters.k=t=>t==null?"undefined":t.toString();C.formatters.a=t=>t==null?"undefined":t.toString();function H(t){let e=me(t.message),r=me(t.stack);return e!=null&&r!=null?r.includes(e)?r:`${e}
|
|
4
|
+
${r}`:r??e??t.toString()}function tt(t){return t?.name==="AggregateError"}C.formatters.e=t=>{if(t==null)return"undefined";if(tt(t)){let e=" ",r=H(t);return t.errors.length>0?r+=`
|
|
5
|
+
${e}${t.errors.map(n=>` ${H(n).split(`
|
|
6
|
+
`).join(`
|
|
7
|
+
${e}`)}`).join(`
|
|
8
|
+
${e}`)}`:r+=`
|
|
9
|
+
${e}[Error list was empty]`,r.trim()}return H(t)};function rt(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function ee(t,e){let r=rt(`${t}:trace`);return C.enabled(`${t}:trace`)&&C.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(r=C(`${t}:trace`,e)),Object.assign(C(t,e),{error:C(`${t}:error`,e),trace:r,newScope:n=>ee(`${t}:${n}`,e)})}function me(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}var ke=Oe(Ee(),1),ut=ee("libp2p:simple-metrics"),P=class{value=0;calculate;constructor(e){this.calculate=e?.calculate}async collect(){return this.calculate!=null?this.calculate():this.value}update(e){this.value=e}increment(e=1){this.value+=e}decrement(e=1){this.value-=e}reset(){this.value=0}timer(){let e=Date.now();return()=>{this.value=Date.now()-e}}},R=class{values={};calculate;constructor(e){this.calculate=e?.calculate}async collect(){return this.calculate!=null?this.calculate():this.values}update(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=n})}increment(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=this.values[r]??0;let i=typeof n=="number"?n:1;this.values[r]+=Number(i)})}decrement(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=this.values[r]??0;let i=typeof n=="number"?n:1;this.values[r]-=Number(i)})}reset(){this.values={}}timer(e){let r=Date.now();return()=>{this.values[e]=Date.now()-r}}},J=class{bucketValues=new Map;countValue=0;sumValue=0;calculate;constructor(e){let r=[...e?.buckets??[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],1/0];for(let n of r)this.bucketValues.set(n,0);this.calculate=e?.calculate}async collect(){return this.calculate!=null&&this.observe(await this.calculate()),{count:this.countValue,sum:this.sumValue,buckets:{...this.bucketValues}}}observe(e){this.countValue++,this.sumValue+=e;for(let[r,n]of this.bucketValues.entries())e<=r&&this.bucketValues.set(r,n+1)}reset(){this.countValue=0,this.sumValue=0;for(let e of this.bucketValues.keys())this.bucketValues.set(e,0)}timer(){let e=Date.now();return()=>{this.observe(Date.now()-e)}}},re=class{histograms={};calculate;constructor(e){this.histograms={},this.calculate=e?.calculate}async collect(){let e={};for(let[r,n]of Object.entries(this.histograms))e[r]=await n.collect();return e}observe(e){for(let[r,n]of Object.entries(e))this.histograms[r]===void 0&&(this.histograms[r]=new J),this.histograms[r].observe(n)}reset(){for(let e of Object.values(this.histograms))e.reset()}timer(e){let r=Date.now();return()=>{this.observe({[e]:Date.now()-r})}}},Q=class{sumValue=0;countValue=0;percentiles;tdigest=new ke.TDigest(.01);compressCount;calculate;constructor(e){this.percentiles=e?.percentiles??[.01,.05,.5,.9,.95,.99,.999],this.compressCount=e?.compressCount??1e3,this.calculate=e?.calculate}async collect(){return this.calculate!=null&&this.observe(await this.calculate()),{count:this.countValue,sum:this.sumValue,percentiles:Object.fromEntries(this.percentiles.map(e=>[e,this.tdigest.percentile(e)]))}}observe(e){this.sumValue+=e,this.countValue++,this.tdigest.push(e),this.tdigest.size()>this.compressCount&&this.tdigest.compress()}reset(){this.sumValue=0,this.countValue=0,this.tdigest.reset()}timer(){let e=Date.now();return()=>{this.observe(Date.now()-e)}}},ne=class{summaries={};opts;constructor(e){this.summaries={},this.opts=e}async collect(){return{...Object.fromEntries(Object.entries(this.summaries).map(([e,r])=>[e,{count:r.countValue,sum:r.sumValue,percentiles:Object.fromEntries(r.percentiles.map(n=>[n,r.tdigest.percentile(n)]))}]))}}observe(e){for(let[r,n]of Object.entries(e))this.summaries[r]===void 0&&(this.summaries[r]=new Q(this.opts)),this.summaries[r].observe(n)}reset(){for(let e of Object.values(this.summaries))e.reset()}timer(e){let r=Date.now();return()=>{this.observe({[e]:Date.now()-r})}}},ie=class{metrics=new Map;transferStats;started;interval;intervalMs;onMetrics;log;constructor(e,r){this.log=e.logger.forComponent("libp2p:simple-metrics"),this.started=!1,this._emitMetrics=this._emitMetrics.bind(this),this.intervalMs=r.intervalMs??1e3,this.onMetrics=r.onMetrics,this.transferStats=new Map}[Symbol.toStringTag]="@libp2p/metrics-simple";[oe]=["@libp2p/metrics"];isStarted(){return this.started}start(){this.started=!0,this.interval=setInterval(this._emitMetrics,this.intervalMs)}stop(){this.started=!1,clearInterval(this.interval),this.transferStats.clear()}_emitMetrics(){Promise.resolve().then(async()=>{let e={};for(let[r,n]of this.metrics.entries())e[r]=await n.collect();this.onMetrics(structuredClone(e))}).catch(e=>{ut.error("could not invoke onMetrics callback - %e",e)})}_incrementValue(e,r){let n=this.transferStats.get(e)??0;this.transferStats.set(e,n+r)}_track(e,r){e.addEventListener("message",i=>{this._incrementValue(`${r} received`,i.data.byteLength)});let n=e.send.bind(e);e.send=i=>(this._incrementValue(`${r} sent`,i.byteLength),n(i))}trackMultiaddrConnection(e){this._track(e,"global")}trackProtocolStream(e){e.protocol!=null&&this._track(e,e.protocol)}registerMetric(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new P(r),this.metrics.set(e,n),n)}registerMetricGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new R(r),this.metrics.set(e,n),n)}registerCounter(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new P(r),this.metrics.set(e,n),n)}registerCounterGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new R(r),this.metrics.set(e,n),n)}registerHistogram(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new J(r),this.metrics.set(e,n),n)}registerHistogramGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new re(r),this.metrics.set(e,n),n)}registerSummary(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new Q(r),this.metrics.set(e,n),n)}registerSummaryGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new ne(r),this.metrics.set(e,n),n)}createTrace(){}traceFunction(e,r){return r}};function ct(t){return e=>new ie(e,t)}return De(lt);})();
|
|
5
10
|
return Libp2PSimpleMetrics}));
|
|
6
11
|
//# sourceMappingURL=index.min.js.map
|
package/dist/index.min.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../node_modules/bintrees/lib/treebase.js", "../../../node_modules/bintrees/lib/rbtree.js", "../../../node_modules/bintrees/lib/bintree.js", "../../../node_modules/bintrees/index.js", "../../../node_modules/tdigest/tdigest.js", "../src/index.ts", "../../interface/src/index.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/weald/node_modules/ms/src/index.ts", "../../../node_modules/weald/src/common.ts", "../../../node_modules/weald/src/browser.ts", "../../../node_modules/weald/src/index.ts", "../../logger/src/index.ts"],
|
|
4
|
-
"sourcesContent": ["\nfunction TreeBase() {}\n\n// removes all nodes from the tree\nTreeBase.prototype.clear = function() {\n this._root = null;\n this.size = 0;\n};\n\n// returns node data if found, null otherwise\nTreeBase.prototype.find = function(data) {\n var res = this._root;\n\n while(res !== null) {\n var c = this._comparator(data, res.data);\n if(c === 0) {\n return res.data;\n }\n else {\n res = res.get_child(c > 0);\n }\n }\n\n return null;\n};\n\n// returns iterator to node if found, null otherwise\nTreeBase.prototype.findIter = function(data) {\n var res = this._root;\n var iter = this.iterator();\n\n while(res !== null) {\n var c = this._comparator(data, res.data);\n if(c === 0) {\n iter._cursor = res;\n return iter;\n }\n else {\n iter._ancestors.push(res);\n res = res.get_child(c > 0);\n }\n }\n\n return null;\n};\n\n// Returns an iterator to the tree node at or immediately after the item\nTreeBase.prototype.lowerBound = function(item) {\n var cur = this._root;\n var iter = this.iterator();\n var cmp = this._comparator;\n\n while(cur !== null) {\n var c = cmp(item, cur.data);\n if(c === 0) {\n iter._cursor = cur;\n return iter;\n }\n iter._ancestors.push(cur);\n cur = cur.get_child(c > 0);\n }\n\n for(var i=iter._ancestors.length - 1; i >= 0; --i) {\n cur = iter._ancestors[i];\n if(cmp(item, cur.data) < 0) {\n iter._cursor = cur;\n iter._ancestors.length = i;\n return iter;\n }\n }\n\n iter._ancestors.length = 0;\n return iter;\n};\n\n// Returns an iterator to the tree node immediately after the item\nTreeBase.prototype.upperBound = function(item) {\n var iter = this.lowerBound(item);\n var cmp = this._comparator;\n\n while(iter.data() !== null && cmp(iter.data(), item) === 0) {\n iter.next();\n }\n\n return iter;\n};\n\n// returns null if tree is empty\nTreeBase.prototype.min = function() {\n var res = this._root;\n if(res === null) {\n return null;\n }\n\n while(res.left !== null) {\n res = res.left;\n }\n\n return res.data;\n};\n\n// returns null if tree is empty\nTreeBase.prototype.max = function() {\n var res = this._root;\n if(res === null) {\n return null;\n }\n\n while(res.right !== null) {\n res = res.right;\n }\n\n return res.data;\n};\n\n// returns a null iterator\n// call next() or prev() to point to an element\nTreeBase.prototype.iterator = function() {\n return new Iterator(this);\n};\n\n// calls cb on each node's data, in order\nTreeBase.prototype.each = function(cb) {\n var it=this.iterator(), data;\n while((data = it.next()) !== null) {\n if(cb(data) === false) {\n return;\n }\n }\n};\n\n// calls cb on each node's data, in reverse order\nTreeBase.prototype.reach = function(cb) {\n var it=this.iterator(), data;\n while((data = it.prev()) !== null) {\n if(cb(data) === false) {\n return;\n }\n }\n};\n\n\nfunction Iterator(tree) {\n this._tree = tree;\n this._ancestors = [];\n this._cursor = null;\n}\n\nIterator.prototype.data = function() {\n return this._cursor !== null ? this._cursor.data : null;\n};\n\n// if null-iterator, returns first node\n// otherwise, returns next node\nIterator.prototype.next = function() {\n if(this._cursor === null) {\n var root = this._tree._root;\n if(root !== null) {\n this._minNode(root);\n }\n }\n else {\n if(this._cursor.right === null) {\n // no greater node in subtree, go up to parent\n // if coming from a right child, continue up the stack\n var save;\n do {\n save = this._cursor;\n if(this._ancestors.length) {\n this._cursor = this._ancestors.pop();\n }\n else {\n this._cursor = null;\n break;\n }\n } while(this._cursor.right === save);\n }\n else {\n // get the next node from the subtree\n this._ancestors.push(this._cursor);\n this._minNode(this._cursor.right);\n }\n }\n return this._cursor !== null ? this._cursor.data : null;\n};\n\n// if null-iterator, returns last node\n// otherwise, returns previous node\nIterator.prototype.prev = function() {\n if(this._cursor === null) {\n var root = this._tree._root;\n if(root !== null) {\n this._maxNode(root);\n }\n }\n else {\n if(this._cursor.left === null) {\n var save;\n do {\n save = this._cursor;\n if(this._ancestors.length) {\n this._cursor = this._ancestors.pop();\n }\n else {\n this._cursor = null;\n break;\n }\n } while(this._cursor.left === save);\n }\n else {\n this._ancestors.push(this._cursor);\n this._maxNode(this._cursor.left);\n }\n }\n return this._cursor !== null ? this._cursor.data : null;\n};\n\nIterator.prototype._minNode = function(start) {\n while(start.left !== null) {\n this._ancestors.push(start);\n start = start.left;\n }\n this._cursor = start;\n};\n\nIterator.prototype._maxNode = function(start) {\n while(start.right !== null) {\n this._ancestors.push(start);\n start = start.right;\n }\n this._cursor = start;\n};\n\nmodule.exports = TreeBase;\n\n", "\nvar TreeBase = require('./treebase');\n\nfunction Node(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n this.red = true;\n}\n\nNode.prototype.get_child = function(dir) {\n return dir ? this.right : this.left;\n};\n\nNode.prototype.set_child = function(dir, val) {\n if(dir) {\n this.right = val;\n }\n else {\n this.left = val;\n }\n};\n\nfunction RBTree(comparator) {\n this._root = null;\n this._comparator = comparator;\n this.size = 0;\n}\n\nRBTree.prototype = new TreeBase();\n\n// returns true if inserted, false if duplicate\nRBTree.prototype.insert = function(data) {\n var ret = false;\n\n if(this._root === null) {\n // empty tree\n this._root = new Node(data);\n ret = true;\n this.size++;\n }\n else {\n var head = new Node(undefined); // fake tree root\n\n var dir = 0;\n var last = 0;\n\n // setup\n var gp = null; // grandparent\n var ggp = head; // grand-grand-parent\n var p = null; // parent\n var node = this._root;\n ggp.right = this._root;\n\n // search down\n while(true) {\n if(node === null) {\n // insert new node at the bottom\n node = new Node(data);\n p.set_child(dir, node);\n ret = true;\n this.size++;\n }\n else if(is_red(node.left) && is_red(node.right)) {\n // color flip\n node.red = true;\n node.left.red = false;\n node.right.red = false;\n }\n\n // fix red violation\n if(is_red(node) && is_red(p)) {\n var dir2 = ggp.right === gp;\n\n if(node === p.get_child(last)) {\n ggp.set_child(dir2, single_rotate(gp, !last));\n }\n else {\n ggp.set_child(dir2, double_rotate(gp, !last));\n }\n }\n\n var cmp = this._comparator(node.data, data);\n\n // stop if found\n if(cmp === 0) {\n break;\n }\n\n last = dir;\n dir = cmp < 0;\n\n // update helpers\n if(gp !== null) {\n ggp = gp;\n }\n gp = p;\n p = node;\n node = node.get_child(dir);\n }\n\n // update root\n this._root = head.right;\n }\n\n // make root black\n this._root.red = false;\n\n return ret;\n};\n\n// returns true if removed, false if not found\nRBTree.prototype.remove = function(data) {\n if(this._root === null) {\n return false;\n }\n\n var head = new Node(undefined); // fake tree root\n var node = head;\n node.right = this._root;\n var p = null; // parent\n var gp = null; // grand parent\n var found = null; // found item\n var dir = 1;\n\n while(node.get_child(dir) !== null) {\n var last = dir;\n\n // update helpers\n gp = p;\n p = node;\n node = node.get_child(dir);\n\n var cmp = this._comparator(data, node.data);\n\n dir = cmp > 0;\n\n // save found node\n if(cmp === 0) {\n found = node;\n }\n\n // push the red node down\n if(!is_red(node) && !is_red(node.get_child(dir))) {\n if(is_red(node.get_child(!dir))) {\n var sr = single_rotate(node, dir);\n p.set_child(last, sr);\n p = sr;\n }\n else if(!is_red(node.get_child(!dir))) {\n var sibling = p.get_child(!last);\n if(sibling !== null) {\n if(!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) {\n // color flip\n p.red = false;\n sibling.red = true;\n node.red = true;\n }\n else {\n var dir2 = gp.right === p;\n\n if(is_red(sibling.get_child(last))) {\n gp.set_child(dir2, double_rotate(p, last));\n }\n else if(is_red(sibling.get_child(!last))) {\n gp.set_child(dir2, single_rotate(p, last));\n }\n\n // ensure correct coloring\n var gpc = gp.get_child(dir2);\n gpc.red = true;\n node.red = true;\n gpc.left.red = false;\n gpc.right.red = false;\n }\n }\n }\n }\n }\n\n // replace and remove if found\n if(found !== null) {\n found.data = node.data;\n p.set_child(p.right === node, node.get_child(node.left === null));\n this.size--;\n }\n\n // update root and make it black\n this._root = head.right;\n if(this._root !== null) {\n this._root.red = false;\n }\n\n return found !== null;\n};\n\nfunction is_red(node) {\n return node !== null && node.red;\n}\n\nfunction single_rotate(root, dir) {\n var save = root.get_child(!dir);\n\n root.set_child(!dir, save.get_child(dir));\n save.set_child(dir, root);\n\n root.red = true;\n save.red = false;\n\n return save;\n}\n\nfunction double_rotate(root, dir) {\n root.set_child(!dir, single_rotate(root.get_child(!dir), !dir));\n return single_rotate(root, dir);\n}\n\nmodule.exports = RBTree;\n", "\nvar TreeBase = require('./treebase');\n\nfunction Node(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n}\n\nNode.prototype.get_child = function(dir) {\n return dir ? this.right : this.left;\n};\n\nNode.prototype.set_child = function(dir, val) {\n if(dir) {\n this.right = val;\n }\n else {\n this.left = val;\n }\n};\n\nfunction BinTree(comparator) {\n this._root = null;\n this._comparator = comparator;\n this.size = 0;\n}\n\nBinTree.prototype = new TreeBase();\n\n// returns true if inserted, false if duplicate\nBinTree.prototype.insert = function(data) {\n if(this._root === null) {\n // empty tree\n this._root = new Node(data);\n this.size++;\n return true;\n }\n\n var dir = 0;\n\n // setup\n var p = null; // parent\n var node = this._root;\n\n // search down\n while(true) {\n if(node === null) {\n // insert new node at the bottom\n node = new Node(data);\n p.set_child(dir, node);\n ret = true;\n this.size++;\n return true;\n }\n\n // stop if found\n if(this._comparator(node.data, data) === 0) {\n return false;\n }\n\n dir = this._comparator(node.data, data) < 0;\n\n // update helpers\n p = node;\n node = node.get_child(dir);\n }\n};\n\n// returns true if removed, false if not found\nBinTree.prototype.remove = function(data) {\n if(this._root === null) {\n return false;\n }\n\n var head = new Node(undefined); // fake tree root\n var node = head;\n node.right = this._root;\n var p = null; // parent\n var found = null; // found item\n var dir = 1;\n\n while(node.get_child(dir) !== null) {\n p = node;\n node = node.get_child(dir);\n var cmp = this._comparator(data, node.data);\n dir = cmp > 0;\n\n if(cmp === 0) {\n found = node;\n }\n }\n\n if(found !== null) {\n found.data = node.data;\n p.set_child(p.right === node, node.get_child(node.left === null));\n\n this._root = head.right;\n this.size--;\n return true;\n }\n else {\n return false;\n }\n};\n\nmodule.exports = BinTree;\n\n", "module.exports = {\n RBTree: require('./lib/rbtree'),\n BinTree: require('./lib/bintree')\n};\n", "//\n// TDigest:\n//\n// approximate distribution percentiles from a stream of reals\n//\nvar RBTree = require('bintrees').RBTree;\n\nfunction TDigest(delta, K, CX) {\n // allocate a TDigest structure.\n //\n // delta is the compression factor, the max fraction of mass that\n // can be owned by one centroid (bigger, up to 1.0, means more\n // compression). delta=false switches off TDigest behavior and treats\n // the distribution as discrete, with no merging and exact values\n // reported.\n //\n // K is a size threshold that triggers recompression as the TDigest\n // grows during input. (Set it to 0 to disable automatic recompression)\n //\n // CX specifies how often to update cached cumulative totals used\n // for quantile estimation during ingest (see cumulate()). Set to\n // 0 to use exact quantiles for each new point.\n //\n this.discrete = (delta === false);\n this.delta = delta || 0.01;\n this.K = (K === undefined) ? 25 : K;\n this.CX = (CX === undefined) ? 1.1 : CX;\n this.centroids = new RBTree(compare_centroid_means);\n this.nreset = 0;\n this.reset();\n}\n\nTDigest.prototype.reset = function() {\n // prepare to digest new points.\n //\n this.centroids.clear();\n this.n = 0;\n this.nreset += 1;\n this.last_cumulate = 0;\n};\n\nTDigest.prototype.size = function() {\n return this.centroids.size;\n};\n\nTDigest.prototype.toArray = function(everything) {\n // return {mean,n} of centroids as an array ordered by mean.\n //\n var result = [];\n if (everything) {\n this._cumulate(true); // be sure cumns are exact\n this.centroids.each(function(c) { result.push(c); });\n } else {\n this.centroids.each(function(c) { result.push({mean:c.mean, n:c.n}); });\n }\n return result;\n};\n\nTDigest.prototype.summary = function() {\n var approx = (this.discrete) ? \"exact \" : \"approximating \";\n var s = [approx + this.n + \" samples using \" + this.size() + \" centroids\",\n \"min = \"+this.percentile(0),\n \"Q1 = \"+this.percentile(0.25),\n \"Q2 = \"+this.percentile(0.5),\n \"Q3 = \"+this.percentile(0.75),\n \"max = \"+this.percentile(1.0)];\n return s.join('\\n');\n};\n\nfunction compare_centroid_means(a, b) {\n // order two centroids by mean.\n //\n return (a.mean > b.mean) ? 1 : (a.mean < b.mean) ? -1 : 0;\n}\n\nfunction compare_centroid_mean_cumns(a, b) {\n // order two centroids by mean_cumn.\n //\n return (a.mean_cumn - b.mean_cumn);\n}\n\nTDigest.prototype.push = function(x, n) {\n // incorporate value or array of values x, having count n into the\n // TDigest. n defaults to 1.\n //\n n = n || 1;\n x = Array.isArray(x) ? x : [x];\n for (var i = 0 ; i < x.length ; i++) {\n this._digest(x[i], n);\n }\n};\n\nTDigest.prototype.push_centroid = function(c) {\n // incorporate centroid or array of centroids c\n //\n c = Array.isArray(c) ? c : [c];\n for (var i = 0 ; i < c.length ; i++) {\n this._digest(c[i].mean, c[i].n);\n }\n};\n\nTDigest.prototype._cumulate = function(exact) {\n // update cumulative counts for each centroid\n //\n // exact: falsey means only cumulate after sufficient\n // growth. During ingest, these counts are used as quantile\n // estimates, and they work well even when somewhat out of\n // date. (this is a departure from the publication, you may set CX\n // to 0 to disable).\n //\n if (this.n === this.last_cumulate ||\n !exact && this.CX && this.CX > (this.n / this.last_cumulate)) {\n return;\n }\n var cumn = 0;\n this.centroids.each(function(c) {\n c.mean_cumn = cumn + c.n / 2; // half of n at the mean\n cumn = c.cumn = cumn + c.n;\n });\n this.n = this.last_cumulate = cumn;\n};\n\nTDigest.prototype.find_nearest = function(x) {\n // find the centroid closest to x. The assumption of\n // unique means and a unique nearest centroid departs from the\n // paper, see _digest() below\n //\n if (this.size() === 0) {\n return null;\n }\n var iter = this.centroids.lowerBound({mean:x}); // x <= iter || iter==null\n var c = (iter.data() === null) ? iter.prev() : iter.data();\n if (c.mean === x || this.discrete) {\n return c; // c is either x or a neighbor (discrete: no distance func)\n }\n var prev = iter.prev();\n if (prev && Math.abs(prev.mean - x) < Math.abs(c.mean - x)) {\n return prev;\n } else {\n return c;\n }\n};\n\nTDigest.prototype._new_centroid = function(x, n, cumn) {\n // create and insert a new centroid into the digest (don't update\n // cumulatives).\n //\n var c = {mean:x, n:n, cumn:cumn};\n this.centroids.insert(c);\n this.n += n;\n return c;\n};\n\nTDigest.prototype._addweight = function(nearest, x, n) {\n // add weight at location x to nearest centroid. adding x to\n // nearest will not shift its relative position in the tree and\n // require reinsertion.\n //\n if (x !== nearest.mean) {\n nearest.mean += n * (x - nearest.mean) / (nearest.n + n);\n }\n nearest.cumn += n;\n nearest.mean_cumn += n / 2;\n nearest.n += n;\n this.n += n;\n};\n\nTDigest.prototype._digest = function(x, n) {\n // incorporate value x, having count n into the TDigest.\n //\n var min = this.centroids.min();\n var max = this.centroids.max();\n var nearest = this.find_nearest(x);\n if (nearest && nearest.mean === x) {\n // accumulate exact matches into the centroid without\n // limit. this is a departure from the paper, made so\n // centroids remain unique and code can be simple.\n this._addweight(nearest, x, n);\n } else if (nearest === min) {\n this._new_centroid(x, n, 0); // new point around min boundary\n } else if (nearest === max ) {\n this._new_centroid(x, n, this.n); // new point around max boundary\n } else if (this.discrete) {\n this._new_centroid(x, n, nearest.cumn); // never merge\n } else {\n // conider a merge based on nearest centroid's capacity. if\n // there's not room for all of n, don't bother merging any of\n // it into nearest, as we'll have to make a new centroid\n // anyway for the remainder (departure from the paper).\n var p = nearest.mean_cumn / this.n;\n var max_n = Math.floor(4 * this.n * this.delta * p * (1 - p));\n if (max_n - nearest.n >= n) {\n this._addweight(nearest, x, n);\n } else {\n this._new_centroid(x, n, nearest.cumn);\n }\n }\n this._cumulate(false);\n if (!this.discrete && this.K && this.size() > this.K / this.delta) {\n // re-process the centroids and hope for some compression.\n this.compress();\n }\n};\n\nTDigest.prototype.bound_mean = function(x) {\n // find centroids lower and upper such that lower.mean < x <\n // upper.mean or lower.mean === x === upper.mean. Don't call\n // this for x out of bounds.\n //\n var iter = this.centroids.upperBound({mean:x}); // x < iter\n var lower = iter.prev(); // lower <= x\n var upper = (lower.mean === x) ? lower : iter.next();\n return [lower, upper];\n};\n\nTDigest.prototype.p_rank = function(x_or_xlist) {\n // return approximate percentile-ranks (0..1) for data value x.\n // or list of x. calculated according to\n // https://en.wikipedia.org/wiki/Percentile_rank\n //\n // (Note that in continuous mode, boundary sample values will\n // report half their centroid weight inward from 0/1 as the\n // percentile-rank. X values outside the observed range return\n // 0/1)\n //\n // this triggers cumulate() if cumn's are out of date.\n //\n var xs = Array.isArray(x_or_xlist) ? x_or_xlist : [x_or_xlist];\n var ps = xs.map(this._p_rank, this);\n return Array.isArray(x_or_xlist) ? ps : ps[0];\n};\n\nTDigest.prototype._p_rank = function(x) {\n if (this.size() === 0) {\n return undefined;\n } else if (x < this.centroids.min().mean) {\n return 0.0;\n } else if (x > this.centroids.max().mean) {\n return 1.0;\n }\n // find centroids that bracket x and interpolate x's cumn from\n // their cumn's.\n this._cumulate(true); // be sure cumns are exact\n var bound = this.bound_mean(x);\n var lower = bound[0], upper = bound[1];\n if (this.discrete) {\n return lower.cumn / this.n;\n } else {\n var cumn = lower.mean_cumn;\n if (lower !== upper) {\n cumn += (x - lower.mean) * (upper.mean_cumn - lower.mean_cumn) / (upper.mean - lower.mean);\n }\n return cumn / this.n;\n }\n};\n\nTDigest.prototype.bound_mean_cumn = function(cumn) {\n // find centroids lower and upper such that lower.mean_cumn < x <\n // upper.mean_cumn or lower.mean_cumn === x === upper.mean_cumn. Don't call\n // this for cumn out of bounds.\n //\n // XXX because mean and mean_cumn give rise to the same sort order\n // (up to identical means), use the mean rbtree for our search.\n this.centroids._comparator = compare_centroid_mean_cumns;\n var iter = this.centroids.upperBound({mean_cumn:cumn}); // cumn < iter\n this.centroids._comparator = compare_centroid_means;\n var lower = iter.prev(); // lower <= cumn\n var upper = (lower && lower.mean_cumn === cumn) ? lower : iter.next();\n return [lower, upper];\n};\n\nTDigest.prototype.percentile = function(p_or_plist) {\n // for percentage p (0..1), or for each p in a list of ps, return\n // the smallest data value q at which at least p percent of the\n // observations <= q.\n //\n // for discrete distributions, this selects q using the Nearest\n // Rank Method\n // (https://en.wikipedia.org/wiki/Percentile#The_Nearest_Rank_method)\n // (in scipy, same as percentile(...., interpolation='higher')\n //\n // for continuous distributions, interpolates data values between\n // count-weighted bracketing means.\n //\n // this triggers cumulate() if cumn's are out of date.\n //\n var ps = Array.isArray(p_or_plist) ? p_or_plist : [p_or_plist];\n var qs = ps.map(this._percentile, this);\n return Array.isArray(p_or_plist) ? qs : qs[0];\n};\n\nTDigest.prototype._percentile = function(p) {\n if (this.size() === 0) {\n return undefined;\n }\n this._cumulate(true); // be sure cumns are exact\n var h = this.n * p;\n var bound = this.bound_mean_cumn(h);\n var lower = bound[0], upper = bound[1];\n\n if (upper === lower || lower === null || upper === null) {\n return (lower || upper).mean;\n } else if (!this.discrete) {\n return lower.mean + (h - lower.mean_cumn) * (upper.mean - lower.mean) / (upper.mean_cumn - lower.mean_cumn);\n } else if (h <= lower.cumn) {\n return lower.mean;\n } else {\n return upper.mean;\n }\n};\n\nfunction pop_random(choices) {\n // remove and return an item randomly chosen from the array of choices\n // (mutates choices)\n //\n var idx = Math.floor(Math.random() * choices.length);\n return choices.splice(idx, 1)[0];\n}\n\nTDigest.prototype.compress = function() {\n // TDigests experience worst case compression (none) when input\n // increases monotonically. Improve on any bad luck by\n // reconsuming digest centroids as if they were weighted points\n // while shuffling their order (and hope for the best).\n //\n if (this.compressing) {\n return;\n }\n var points = this.toArray();\n this.reset();\n this.compressing = true;\n while (points.length > 0) {\n this.push_centroid(pop_random(points));\n }\n this._cumulate(true);\n this.compressing = false;\n};\n\nfunction Digest(config) {\n // allocate a distribution digest structure. This is an extension\n // of a TDigest structure that starts in exact histogram (discrete)\n // mode, and automatically switches to TDigest mode for large\n // samples that appear to be from a continuous distribution.\n //\n this.config = config || {};\n this.mode = this.config.mode || 'auto'; // disc, cont, auto\n TDigest.call(this, this.mode === 'cont' ? config.delta : false);\n this.digest_ratio = this.config.ratio || 0.9;\n this.digest_thresh = this.config.thresh || 1000;\n this.n_unique = 0;\n}\nDigest.prototype = Object.create(TDigest.prototype);\nDigest.prototype.constructor = Digest;\n\nDigest.prototype.push = function(x_or_xlist) {\n TDigest.prototype.push.call(this, x_or_xlist);\n this.check_continuous();\n};\n\nDigest.prototype._new_centroid = function(x, n, cumn) {\n this.n_unique += 1;\n TDigest.prototype._new_centroid.call(this, x, n, cumn);\n};\n\nDigest.prototype._addweight = function(nearest, x, n) {\n if (nearest.n === 1) {\n this.n_unique -= 1;\n }\n TDigest.prototype._addweight.call(this, nearest, x, n);\n};\n\nDigest.prototype.check_continuous = function() {\n // while in 'auto' mode, if there are many unique elements, assume\n // they are from a continuous distribution and switch to 'cont'\n // mode (tdigest behavior). Return true on transition from\n // disctete to continuous.\n if (this.mode !== 'auto' || this.size() < this.digest_thresh) {\n return false;\n }\n if (this.n_unique / this.size() > this.digest_ratio) {\n this.mode = 'cont';\n this.discrete = false;\n this.delta = this.config.delta || 0.01;\n this.compress();\n return true;\n }\n return false;\n};\n\nmodule.exports = {\n 'TDigest': TDigest,\n 'Digest': Digest\n};\n", "/**\n * @packageDocumentation\n *\n * Stores metrics in memory and periodically invokes a configured callback to\n * receive them.\n *\n * @example\n *\n * ```ts\n * import { createLibp2p } from 'libp2p'\n * import { simpleMetrics } from '@libp2p/simple-metrics'\n *\n * const node = await createLibp2p({\n * // ... other options\n * metrics: simpleMetrics({\n * onMetrics: (metrics) => {\n * // do something with metrics\n * }\n * }),\n * intervalMs: 1000 // default 1s\n * })\n *\n * ```\n */\n\nimport { serviceCapabilities } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport { TDigest } from 'tdigest'\nimport type { Startable, MultiaddrConnection, Stream, Metric, MetricGroup, StopTimer, Metrics, CalculatedMetricOptions, MetricOptions, Counter, CounterGroup, CalculateMetric, Histogram, HistogramOptions, HistogramGroup, Summary, SummaryOptions, SummaryGroup, CalculatedHistogramOptions, CalculatedSummaryOptions, ComponentLogger, Logger, MessageStream } from '@libp2p/interface'\n\nconst log = logger('libp2p:simple-metrics')\n\nclass SimpleMetric implements Metric {\n private value: number = 0\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedMetricOptions) {\n this.calculate = opts?.calculate\n }\n\n async collect (): Promise<number> {\n if (this.calculate != null) {\n return this.calculate()\n }\n\n return this.value\n }\n\n update (value: number): void {\n this.value = value\n }\n\n increment (value: number = 1): void {\n this.value += value\n }\n\n decrement (value: number = 1): void {\n this.value -= value\n }\n\n reset (): void {\n this.value = 0\n }\n\n timer (): StopTimer {\n const start = Date.now()\n\n return () => {\n this.value = Date.now() - start\n }\n }\n}\n\nclass SimpleGroupMetric implements MetricGroup {\n private values: Record<string, number> = {}\n private readonly calculate?: CalculateMetric<Record<string, number>>\n\n constructor (opts?: CalculatedMetricOptions<Record<string, number>>) {\n this.calculate = opts?.calculate\n }\n\n async collect (): Promise<Record<string, number>> {\n if (this.calculate != null) {\n return this.calculate()\n }\n\n return this.values\n }\n\n update (values: Record<string, number>): void {\n Object.entries(values).forEach(([key, value]) => {\n this.values[key] = value\n })\n }\n\n increment (values: Record<string, number | unknown>): void {\n Object.entries(values).forEach(([key, value]) => {\n this.values[key] = this.values[key] ?? 0\n const inc = typeof value === 'number' ? value : 1\n\n this.values[key] += Number(inc)\n })\n }\n\n decrement (values: Record<string, number | unknown>): void {\n Object.entries(values).forEach(([key, value]) => {\n this.values[key] = this.values[key] ?? 0\n const dec = typeof value === 'number' ? value : 1\n\n this.values[key] -= Number(dec)\n })\n }\n\n reset (): void {\n this.values = {}\n }\n\n timer (key: string): StopTimer {\n const start = Date.now()\n\n return () => {\n this.values[key] = Date.now() - start\n }\n }\n}\n\nclass SimpleHistogram implements Histogram {\n private bucketValues = new Map<number, number>()\n private countValue: number = 0\n private sumValue: number = 0\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedHistogramOptions) {\n const buckets = [\n ...(opts?.buckets ?? [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]),\n Infinity\n ]\n for (const bucket of buckets) {\n this.bucketValues.set(bucket, 0)\n }\n this.calculate = opts?.calculate\n }\n\n public async collect (): Promise<{ count: number, sum: number, buckets: Record<number, number> }> {\n if (this.calculate != null) {\n this.observe(await this.calculate())\n }\n\n return {\n count: this.countValue,\n sum: this.sumValue,\n buckets: { ...this.bucketValues }\n }\n }\n\n observe (value: number): void {\n this.countValue++\n this.sumValue += value\n\n for (const [bucket, count] of this.bucketValues.entries()) {\n if (value <= bucket) {\n this.bucketValues.set(bucket, count + 1)\n }\n }\n }\n\n reset (): void {\n this.countValue = 0\n this.sumValue = 0\n for (const bucket of this.bucketValues.keys()) {\n this.bucketValues.set(bucket, 0)\n }\n }\n\n timer (): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe(Date.now() - start)\n }\n }\n}\n\nclass SimpleHistogramGroup implements HistogramGroup {\n public histograms: Record<string, SimpleHistogram> = {}\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedHistogramOptions) {\n this.histograms = {}\n this.calculate = opts?.calculate\n }\n\n public async collect (): Promise<Record<string, { count: number, sum: number, buckets: Record<number, number> }>> {\n const output: Record<string, { count: number, sum: number, buckets: Record<number, number> }> = {}\n\n for (const [key, histogram] of Object.entries(this.histograms)) {\n output[key] = await histogram.collect()\n }\n\n return output\n }\n\n observe (values: Partial<Record<string, number>>): void {\n for (const [key, value] of Object.entries(values) as Array<[string, number]>) {\n if (this.histograms[key] === undefined) {\n this.histograms[key] = new SimpleHistogram()\n }\n\n this.histograms[key].observe(value)\n }\n }\n\n reset (): void {\n for (const histogram of Object.values(this.histograms)) {\n histogram.reset()\n }\n }\n\n timer (key: string): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe({ [key]: Date.now() - start })\n }\n }\n}\n\nclass SimpleSummary implements Summary {\n public sumValue: number = 0\n public countValue: number = 0\n public percentiles: number[]\n public tdigest = new TDigest(0.01)\n private readonly compressCount: number\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedSummaryOptions) {\n this.percentiles = opts?.percentiles ?? [0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999]\n this.compressCount = opts?.compressCount ?? 1000\n this.calculate = opts?.calculate\n }\n\n public async collect (): Promise<{ count: number, sum: number, percentiles: Record<string, number> }> {\n if (this.calculate != null) {\n this.observe(await this.calculate())\n }\n\n return {\n count: this.countValue,\n sum: this.sumValue,\n percentiles: Object.fromEntries(this.percentiles.map(p => [p, this.tdigest.percentile(p)]))\n }\n }\n\n observe (value: number): void {\n this.sumValue += value\n this.countValue++\n\n this.tdigest.push(value)\n if (this.tdigest.size() > this.compressCount) {\n this.tdigest.compress()\n }\n }\n\n reset (): void {\n this.sumValue = 0\n this.countValue = 0\n\n this.tdigest.reset()\n }\n\n timer (): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe(Date.now() - start)\n }\n }\n}\n\nclass SimpleSummaryGroup implements SummaryGroup {\n public summaries: Record<string, SimpleSummary> = {}\n private readonly opts?: CalculatedSummaryOptions\n\n constructor (opts?: CalculatedSummaryOptions) {\n this.summaries = {}\n this.opts = opts\n }\n\n public async collect (): Promise<Record<string, { count: number, sum: number, percentiles: Record<string, number> }>> {\n return {\n ...Object.fromEntries(Object.entries(this.summaries).map(([key, summary]) => {\n return [key, {\n count: summary.countValue,\n sum: summary.sumValue,\n percentiles: Object.fromEntries(summary.percentiles.map(p => [p, summary.tdigest.percentile(p)]))\n }]\n }))\n }\n }\n\n observe (values: Record<string, number>): void {\n for (const [key, value] of Object.entries(values)) {\n if (this.summaries[key] === undefined) {\n this.summaries[key] = new SimpleSummary(this.opts)\n }\n\n this.summaries[key].observe(value)\n }\n }\n\n reset (): void {\n for (const summary of Object.values(this.summaries)) {\n summary.reset()\n }\n }\n\n timer (key: string): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe({ [key]: Date.now() - start })\n }\n }\n}\n\nexport interface OnMetrics { (metrics: Record<string, any>): void }\n\nexport interface SimpleMetricsInit {\n /**\n * How often to invoke the onMetrics callback\n */\n intervalMs?: number\n\n /**\n * A callback periodically invoked with collected metrics\n */\n onMetrics: OnMetrics\n}\n\nexport interface SimpleMetricsComponents {\n logger: ComponentLogger\n}\n\nclass SimpleMetrics implements Metrics, Startable {\n public metrics = new Map<string, SimpleMetric | SimpleGroupMetric | SimpleHistogram | SimpleHistogramGroup | SimpleSummary | SimpleSummaryGroup>()\n private readonly transferStats: Map<string, number>\n private started: boolean\n private interval?: ReturnType<typeof setInterval>\n private readonly intervalMs: number\n private readonly onMetrics: OnMetrics\n private readonly log: Logger\n\n constructor (components: SimpleMetricsComponents, init: SimpleMetricsInit) {\n this.log = components.logger.forComponent('libp2p:simple-metrics')\n this.started = false\n\n this._emitMetrics = this._emitMetrics.bind(this)\n\n this.intervalMs = init.intervalMs ?? 1000\n this.onMetrics = init.onMetrics\n\n // holds global and per-protocol sent/received stats\n this.transferStats = new Map()\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/metrics-simple'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/metrics'\n ]\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n\n this.interval = setInterval(this._emitMetrics, this.intervalMs)\n }\n\n stop (): void {\n this.started = false\n\n clearInterval(this.interval)\n this.transferStats.clear()\n }\n\n private _emitMetrics (): void {\n Promise.resolve().then(async () => {\n const output: Record<string, any> = {}\n\n for (const [name, metric] of this.metrics.entries()) {\n output[name] = await metric.collect()\n }\n\n this.onMetrics(structuredClone(output))\n })\n .catch(err => {\n log.error('could not invoke onMetrics callback - %e', err)\n })\n }\n\n /**\n * Increment the transfer stat for the passed key, making sure\n * it exists first\n */\n _incrementValue (key: string, value: number): void {\n const existing = this.transferStats.get(key) ?? 0\n\n this.transferStats.set(key, existing + value)\n }\n\n /**\n * Override the sink/source of the stream to count the bytes\n * in and out\n */\n _track (stream: MessageStream, name: string): void {\n stream.addEventListener('message', (evt) => {\n this._incrementValue(`${name} received`, evt.data.byteLength)\n })\n\n const send = stream.send.bind(stream)\n stream.send = (buf) => {\n this._incrementValue(`${name} sent`, buf.byteLength)\n\n return send(buf)\n }\n }\n\n trackMultiaddrConnection (maConn: MultiaddrConnection): void {\n this._track(maConn, 'global')\n }\n\n trackProtocolStream (stream: Stream): void {\n if (stream.protocol == null) {\n // protocol not negotiated yet, should not happen as the upgrader\n // calls this handler after protocol negotiation\n return\n }\n\n this._track(stream, stream.protocol)\n }\n\n registerMetric (name: string, opts: CalculatedMetricOptions): void\n registerMetric (name: string, opts?: MetricOptions): Metric\n registerMetric (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerMetricGroup (name: string, opts: CalculatedMetricOptions<Record<string, number>>): void\n registerMetricGroup (name: string, opts?: MetricOptions): MetricGroup\n registerMetricGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleGroupMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerCounter (name: string, opts: CalculatedMetricOptions): void\n registerCounter (name: string, opts?: MetricOptions): Counter\n registerCounter (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerCounterGroup (name: string, opts: CalculatedMetricOptions<Record<string, number>>): void\n registerCounterGroup (name: string, opts?: MetricOptions): CounterGroup\n registerCounterGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleGroupMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerHistogram (name: string, opts: CalculatedHistogramOptions): void\n registerHistogram (name: string, opts?: HistogramOptions): Histogram\n registerHistogram (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleHistogram(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerHistogramGroup (name: string, opts: CalculatedHistogramOptions<Record<string, number>>): void\n registerHistogramGroup (name: string, opts?: HistogramOptions): HistogramGroup\n registerHistogramGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleHistogramGroup(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerSummary (name: string, opts: CalculatedSummaryOptions): void\n registerSummary (name: string, opts?: SummaryOptions): Summary\n registerSummary (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleSummary(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerSummaryGroup (name: string, opts: CalculatedSummaryOptions<Record<string, number>>): void\n registerSummaryGroup (name: string, opts?: SummaryOptions): SummaryGroup\n registerSummaryGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleSummaryGroup(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n createTrace (): any {\n // no-op\n }\n\n traceFunction <T extends (...args: any[]) => any> (name: string, fn: T): T {\n // no-op\n return fn\n }\n}\n\nexport function simpleMetrics (init: SimpleMetricsInit): (components: SimpleMetricsComponents) => Metrics {\n return (components) => new SimpleMetrics(components, init)\n}\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.js'\nimport type { Stream } from './stream.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './connection-protector.js'\nexport * from './content-routing.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './keys.js'\nexport * from './message-stream.js'\nexport * from './metrics.js'\nexport * from './multiaddr-connection.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './record.js'\nexport * from './startable.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './stream.js'\nexport * from './topology.js'\nexport * from './transport.js'\n\nexport * from 'main-event'\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { return new Uint8Array(o) }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "const s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nconst mo = y / 12;\n\ntype Years = 'years' | 'year' | 'yrs' | 'yr' | 'y';\ntype Months = 'months' | 'month' | 'mo';\ntype Weeks = 'weeks' | 'week' | 'w';\ntype Days = 'days' | 'day' | 'd';\ntype Hours = 'hours' | 'hour' | 'hrs' | 'hr' | 'h';\ntype Minutes = 'minutes' | 'minute' | 'mins' | 'min' | 'm';\ntype Seconds = 'seconds' | 'second' | 'secs' | 'sec' | 's';\ntype Milliseconds = 'milliseconds' | 'millisecond' | 'msecs' | 'msec' | 'ms';\ntype Unit =\n | Years\n | Months\n | Weeks\n | Days\n | Hours\n | Minutes\n | Seconds\n | Milliseconds;\n\ntype UnitAnyCase = Capitalize<Unit> | Uppercase<Unit> | Unit;\n\nexport type StringValue =\n | `${number}`\n | `${number}${UnitAnyCase}`\n | `${number} ${UnitAnyCase}`;\n\ninterface Options {\n /**\n * Set to `true` to use verbose formatting. Defaults to `false`.\n */\n long?: boolean;\n}\n\n/**\n * Parse or format the given value.\n *\n * @param value - The string or number to convert\n * @param options - Options for the conversion\n * @throws Error if `value` is not a non-empty string or a number\n */\nexport function ms(value: StringValue, options?: Options): number;\nexport function ms(value: number, options?: Options): string;\nexport function ms(\n value: StringValue | number,\n options?: Options,\n): number | string {\n if (typeof value === 'string') {\n return parse(value);\n } else if (typeof value === 'number') {\n return format(value, options);\n }\n throw new Error(\n `Value provided to ms() must be a string or number. value=${JSON.stringify(value)}`,\n );\n}\n\nexport default ms;\n\n/**\n * Parse the given string and return milliseconds.\n *\n * @param str - A string to parse to milliseconds\n * @returns The parsed value in milliseconds, or `NaN` if the string can't be\n * parsed\n */\nexport function parse(str: string): number {\n if (typeof str !== 'string' || str.length === 0 || str.length > 100) {\n throw new Error(\n `Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(str)}`,\n );\n }\n const match =\n /^(?<value>-?\\d*\\.?\\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(\n str,\n );\n\n if (!match?.groups) {\n return NaN;\n }\n\n // Named capture groups need to be manually typed today.\n // https://github.com/microsoft/TypeScript/issues/32098\n const { value, unit = 'ms' } = match.groups as {\n value: string;\n unit: string | undefined;\n };\n\n const n = parseFloat(value);\n\n const matchUnit = unit.toLowerCase() as Lowercase<Unit>;\n\n /* istanbul ignore next - istanbul doesn't understand, but thankfully the TypeScript the exhaustiveness check in the default case keeps us type safe here */\n switch (matchUnit) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'months':\n case 'month':\n case 'mo':\n return n * mo;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n matchUnit satisfies never;\n throw new Error(\n `Unknown unit \"${matchUnit}\" provided to ms.parse(). value=${JSON.stringify(str)}`,\n );\n }\n}\n\n/**\n * Parse the given StringValue and return milliseconds.\n *\n * @param value - A typesafe StringValue to parse to milliseconds\n * @returns The parsed value in milliseconds, or `NaN` if the string can't be\n * parsed\n */\nexport function parseStrict(value: StringValue): number {\n return parse(value);\n}\n\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms: number): StringValue {\n const msAbs = Math.abs(ms);\n if (msAbs >= y) {\n return `${Math.round(ms / y)}y`;\n }\n if (msAbs >= mo) {\n return `${Math.round(ms / mo)}mo`;\n }\n if (msAbs >= w) {\n return `${Math.round(ms / w)}w`;\n }\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms: number): StringValue {\n const msAbs = Math.abs(ms);\n if (msAbs >= y) {\n return plural(ms, msAbs, y, 'year');\n }\n if (msAbs >= mo) {\n return plural(ms, msAbs, mo, 'month');\n }\n if (msAbs >= w) {\n return plural(ms, msAbs, w, 'week');\n }\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n\n/**\n * Format the given integer as a string.\n *\n * @param ms - milliseconds\n * @param options - Options for the conversion\n * @returns The formatted string\n */\nexport function format(ms: number, options?: Options): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) {\n throw new Error('Value provided to ms.format() must be of type number.');\n }\n\n return options?.long ? fmtLong(ms) : fmtShort(ms);\n}\n\n/**\n * Pluralization helper.\n */\nfunction plural(\n ms: number,\n msAbs: number,\n n: number,\n name: string,\n): StringValue {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}` as StringValue;\n}\n", "/* eslint-disable no-console */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms'\nimport type { Debug, Debugger } from './index.js'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms'\nimport setup from './common.js'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.js'\nimport type ms from 'ms'\n\nexport interface Debug {\n (namespace: string): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(...args: any[]): any\n selectColor(namespace: string): string | number\n humanize: typeof ms\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(...args: any[]): any\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %e', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId, Logger, ComponentLogger } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n if (v == null) {\n return 'undefined'\n }\n\n const message = notEmpty(v.message)\n const stack = notEmpty(v.stack)\n\n // some browser errors (mostly from Firefox) have no message or no stack,\n // sometimes both, sometimes neither. Sometimes the message is in the stack,\n // sometimes is isn't so try to do *something* useful\n if (message != null && stack != null) {\n if (stack.includes(message)) {\n return stack\n }\n\n return `${message}\\n${stack}`\n }\n\n if (stack != null) {\n return stack\n }\n\n if (message != null) {\n return message\n }\n\n return v.toString()\n}\n\nexport type { Logger, ComponentLogger }\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial<PeerLoggerOptions> = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`)\n }\n\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n"],
|
|
5
|
-
"mappings": ";kqBAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,CACA,SAASC,GAAW,CAAC,CAGrBA,EAAS,UAAU,MAAQ,UAAW,CAClC,KAAK,MAAQ,KACb,KAAK,KAAO,CAChB,EAGAA,EAAS,UAAU,KAAO,SAASC,EAAM,CAGrC,QAFIC,EAAM,KAAK,MAETA,IAAQ,MAAM,CAChB,IAAIC,EAAI,KAAK,YAAYF,EAAMC,EAAI,IAAI,EACvC,GAAGC,IAAM,EACL,OAAOD,EAAI,KAGXA,EAAMA,EAAI,UAAUC,EAAI,CAAC,CAEjC,CAEA,OAAO,IACX,EAGAH,EAAS,UAAU,SAAW,SAASC,EAAM,CAIzC,QAHIC,EAAM,KAAK,MACXE,EAAO,KAAK,SAAS,EAEnBF,IAAQ,MAAM,CAChB,IAAIC,EAAI,KAAK,YAAYF,EAAMC,EAAI,IAAI,EACvC,GAAGC,IAAM,EACL,OAAAC,EAAK,QAAUF,EACRE,EAGPA,EAAK,WAAW,KAAKF,CAAG,EACxBA,EAAMA,EAAI,UAAUC,EAAI,CAAC,CAEjC,CAEA,OAAO,IACX,EAGAH,EAAS,UAAU,WAAa,SAASK,EAAM,CAK3C,QAJIC,EAAM,KAAK,MACXF,EAAO,KAAK,SAAS,EACrBG,EAAM,KAAK,YAETD,IAAQ,MAAM,CAChB,IAAIH,EAAII,EAAIF,EAAMC,EAAI,IAAI,EAC1B,GAAGH,IAAM,EACL,OAAAC,EAAK,QAAUE,EACRF,EAEXA,EAAK,WAAW,KAAKE,CAAG,EACxBA,EAAMA,EAAI,UAAUH,EAAI,CAAC,CAC7B,CAEA,QAAQK,EAAEJ,EAAK,WAAW,OAAS,EAAGI,GAAK,EAAG,EAAEA,EAE5C,GADAF,EAAMF,EAAK,WAAWI,CAAC,EACpBD,EAAIF,EAAM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", "it", "tree", "root", "save", "start", "require_rbtree", "__commonJSMin", "exports", "module", "TreeBase", "Node", "data", "dir", "val", "RBTree", "comparator", "ret", "head", "last", "gp", "ggp", "p", "node", "is_red", "dir2", "single_rotate", "double_rotate", "cmp", "found", "sr", "sibling", "gpc", "root", "save", "require_bintree", "__commonJSMin", "exports", "module", "TreeBase", "Node", "data", "dir", "val", "BinTree", "comparator", "p", "node", "head", "found", "cmp", "require_bintrees", "__commonJSMin", "exports", "module", "require_tdigest", "__commonJSMin", "exports", "module", "RBTree", "TDigest", "delta", "K", "CX", "compare_centroid_means", "everything", "result", "c", "approx", "s", "a", "b", "compare_centroid_mean_cumns", "x", "n", "i", "exact", "cumn", "iter", "prev", "nearest", "min", "max", "p", "max_n", "lower", "upper", "x_or_xlist", "xs", "ps", "bound", "p_or_plist", "qs", "h", "pop_random", "choices", "idx", "points", "Digest", "config", "index_exports", "__export", "simpleMetrics", "serviceCapabilities", "serviceDependencies", "empty", "coerce", "o", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base58btc", "baseX", "base58flickr", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "s", "value: StringValue | number", "options?: Options", "e", "l", "p", "t", "c", "str: string", "u", "d", "f", "d", "ms: number", "c", "ms", "f", "m", "p", "options?: Options", "t", "msAbs: number", "n: number", "name: string", "n", "r", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "c", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "storage", "localstorage", "colors", "useColors", "formatArgs", "args", "c", "index", "lastC", "match", "log", "save", "namespaces", "load", "r", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "src_default", "v", "base58btc", "base32", "base64", "message", "notEmpty", "stack", "createDisabledLogger", "namespace", "logger", "logger", "name", "trace", "createDisabledLogger", "src_default", "
|
|
4
|
+
"sourcesContent": ["\nfunction TreeBase() {}\n\n// removes all nodes from the tree\nTreeBase.prototype.clear = function() {\n this._root = null;\n this.size = 0;\n};\n\n// returns node data if found, null otherwise\nTreeBase.prototype.find = function(data) {\n var res = this._root;\n\n while(res !== null) {\n var c = this._comparator(data, res.data);\n if(c === 0) {\n return res.data;\n }\n else {\n res = res.get_child(c > 0);\n }\n }\n\n return null;\n};\n\n// returns iterator to node if found, null otherwise\nTreeBase.prototype.findIter = function(data) {\n var res = this._root;\n var iter = this.iterator();\n\n while(res !== null) {\n var c = this._comparator(data, res.data);\n if(c === 0) {\n iter._cursor = res;\n return iter;\n }\n else {\n iter._ancestors.push(res);\n res = res.get_child(c > 0);\n }\n }\n\n return null;\n};\n\n// Returns an iterator to the tree node at or immediately after the item\nTreeBase.prototype.lowerBound = function(item) {\n var cur = this._root;\n var iter = this.iterator();\n var cmp = this._comparator;\n\n while(cur !== null) {\n var c = cmp(item, cur.data);\n if(c === 0) {\n iter._cursor = cur;\n return iter;\n }\n iter._ancestors.push(cur);\n cur = cur.get_child(c > 0);\n }\n\n for(var i=iter._ancestors.length - 1; i >= 0; --i) {\n cur = iter._ancestors[i];\n if(cmp(item, cur.data) < 0) {\n iter._cursor = cur;\n iter._ancestors.length = i;\n return iter;\n }\n }\n\n iter._ancestors.length = 0;\n return iter;\n};\n\n// Returns an iterator to the tree node immediately after the item\nTreeBase.prototype.upperBound = function(item) {\n var iter = this.lowerBound(item);\n var cmp = this._comparator;\n\n while(iter.data() !== null && cmp(iter.data(), item) === 0) {\n iter.next();\n }\n\n return iter;\n};\n\n// returns null if tree is empty\nTreeBase.prototype.min = function() {\n var res = this._root;\n if(res === null) {\n return null;\n }\n\n while(res.left !== null) {\n res = res.left;\n }\n\n return res.data;\n};\n\n// returns null if tree is empty\nTreeBase.prototype.max = function() {\n var res = this._root;\n if(res === null) {\n return null;\n }\n\n while(res.right !== null) {\n res = res.right;\n }\n\n return res.data;\n};\n\n// returns a null iterator\n// call next() or prev() to point to an element\nTreeBase.prototype.iterator = function() {\n return new Iterator(this);\n};\n\n// calls cb on each node's data, in order\nTreeBase.prototype.each = function(cb) {\n var it=this.iterator(), data;\n while((data = it.next()) !== null) {\n if(cb(data) === false) {\n return;\n }\n }\n};\n\n// calls cb on each node's data, in reverse order\nTreeBase.prototype.reach = function(cb) {\n var it=this.iterator(), data;\n while((data = it.prev()) !== null) {\n if(cb(data) === false) {\n return;\n }\n }\n};\n\n\nfunction Iterator(tree) {\n this._tree = tree;\n this._ancestors = [];\n this._cursor = null;\n}\n\nIterator.prototype.data = function() {\n return this._cursor !== null ? this._cursor.data : null;\n};\n\n// if null-iterator, returns first node\n// otherwise, returns next node\nIterator.prototype.next = function() {\n if(this._cursor === null) {\n var root = this._tree._root;\n if(root !== null) {\n this._minNode(root);\n }\n }\n else {\n if(this._cursor.right === null) {\n // no greater node in subtree, go up to parent\n // if coming from a right child, continue up the stack\n var save;\n do {\n save = this._cursor;\n if(this._ancestors.length) {\n this._cursor = this._ancestors.pop();\n }\n else {\n this._cursor = null;\n break;\n }\n } while(this._cursor.right === save);\n }\n else {\n // get the next node from the subtree\n this._ancestors.push(this._cursor);\n this._minNode(this._cursor.right);\n }\n }\n return this._cursor !== null ? this._cursor.data : null;\n};\n\n// if null-iterator, returns last node\n// otherwise, returns previous node\nIterator.prototype.prev = function() {\n if(this._cursor === null) {\n var root = this._tree._root;\n if(root !== null) {\n this._maxNode(root);\n }\n }\n else {\n if(this._cursor.left === null) {\n var save;\n do {\n save = this._cursor;\n if(this._ancestors.length) {\n this._cursor = this._ancestors.pop();\n }\n else {\n this._cursor = null;\n break;\n }\n } while(this._cursor.left === save);\n }\n else {\n this._ancestors.push(this._cursor);\n this._maxNode(this._cursor.left);\n }\n }\n return this._cursor !== null ? this._cursor.data : null;\n};\n\nIterator.prototype._minNode = function(start) {\n while(start.left !== null) {\n this._ancestors.push(start);\n start = start.left;\n }\n this._cursor = start;\n};\n\nIterator.prototype._maxNode = function(start) {\n while(start.right !== null) {\n this._ancestors.push(start);\n start = start.right;\n }\n this._cursor = start;\n};\n\nmodule.exports = TreeBase;\n\n", "\nvar TreeBase = require('./treebase');\n\nfunction Node(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n this.red = true;\n}\n\nNode.prototype.get_child = function(dir) {\n return dir ? this.right : this.left;\n};\n\nNode.prototype.set_child = function(dir, val) {\n if(dir) {\n this.right = val;\n }\n else {\n this.left = val;\n }\n};\n\nfunction RBTree(comparator) {\n this._root = null;\n this._comparator = comparator;\n this.size = 0;\n}\n\nRBTree.prototype = new TreeBase();\n\n// returns true if inserted, false if duplicate\nRBTree.prototype.insert = function(data) {\n var ret = false;\n\n if(this._root === null) {\n // empty tree\n this._root = new Node(data);\n ret = true;\n this.size++;\n }\n else {\n var head = new Node(undefined); // fake tree root\n\n var dir = 0;\n var last = 0;\n\n // setup\n var gp = null; // grandparent\n var ggp = head; // grand-grand-parent\n var p = null; // parent\n var node = this._root;\n ggp.right = this._root;\n\n // search down\n while(true) {\n if(node === null) {\n // insert new node at the bottom\n node = new Node(data);\n p.set_child(dir, node);\n ret = true;\n this.size++;\n }\n else if(is_red(node.left) && is_red(node.right)) {\n // color flip\n node.red = true;\n node.left.red = false;\n node.right.red = false;\n }\n\n // fix red violation\n if(is_red(node) && is_red(p)) {\n var dir2 = ggp.right === gp;\n\n if(node === p.get_child(last)) {\n ggp.set_child(dir2, single_rotate(gp, !last));\n }\n else {\n ggp.set_child(dir2, double_rotate(gp, !last));\n }\n }\n\n var cmp = this._comparator(node.data, data);\n\n // stop if found\n if(cmp === 0) {\n break;\n }\n\n last = dir;\n dir = cmp < 0;\n\n // update helpers\n if(gp !== null) {\n ggp = gp;\n }\n gp = p;\n p = node;\n node = node.get_child(dir);\n }\n\n // update root\n this._root = head.right;\n }\n\n // make root black\n this._root.red = false;\n\n return ret;\n};\n\n// returns true if removed, false if not found\nRBTree.prototype.remove = function(data) {\n if(this._root === null) {\n return false;\n }\n\n var head = new Node(undefined); // fake tree root\n var node = head;\n node.right = this._root;\n var p = null; // parent\n var gp = null; // grand parent\n var found = null; // found item\n var dir = 1;\n\n while(node.get_child(dir) !== null) {\n var last = dir;\n\n // update helpers\n gp = p;\n p = node;\n node = node.get_child(dir);\n\n var cmp = this._comparator(data, node.data);\n\n dir = cmp > 0;\n\n // save found node\n if(cmp === 0) {\n found = node;\n }\n\n // push the red node down\n if(!is_red(node) && !is_red(node.get_child(dir))) {\n if(is_red(node.get_child(!dir))) {\n var sr = single_rotate(node, dir);\n p.set_child(last, sr);\n p = sr;\n }\n else if(!is_red(node.get_child(!dir))) {\n var sibling = p.get_child(!last);\n if(sibling !== null) {\n if(!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) {\n // color flip\n p.red = false;\n sibling.red = true;\n node.red = true;\n }\n else {\n var dir2 = gp.right === p;\n\n if(is_red(sibling.get_child(last))) {\n gp.set_child(dir2, double_rotate(p, last));\n }\n else if(is_red(sibling.get_child(!last))) {\n gp.set_child(dir2, single_rotate(p, last));\n }\n\n // ensure correct coloring\n var gpc = gp.get_child(dir2);\n gpc.red = true;\n node.red = true;\n gpc.left.red = false;\n gpc.right.red = false;\n }\n }\n }\n }\n }\n\n // replace and remove if found\n if(found !== null) {\n found.data = node.data;\n p.set_child(p.right === node, node.get_child(node.left === null));\n this.size--;\n }\n\n // update root and make it black\n this._root = head.right;\n if(this._root !== null) {\n this._root.red = false;\n }\n\n return found !== null;\n};\n\nfunction is_red(node) {\n return node !== null && node.red;\n}\n\nfunction single_rotate(root, dir) {\n var save = root.get_child(!dir);\n\n root.set_child(!dir, save.get_child(dir));\n save.set_child(dir, root);\n\n root.red = true;\n save.red = false;\n\n return save;\n}\n\nfunction double_rotate(root, dir) {\n root.set_child(!dir, single_rotate(root.get_child(!dir), !dir));\n return single_rotate(root, dir);\n}\n\nmodule.exports = RBTree;\n", "\nvar TreeBase = require('./treebase');\n\nfunction Node(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n}\n\nNode.prototype.get_child = function(dir) {\n return dir ? this.right : this.left;\n};\n\nNode.prototype.set_child = function(dir, val) {\n if(dir) {\n this.right = val;\n }\n else {\n this.left = val;\n }\n};\n\nfunction BinTree(comparator) {\n this._root = null;\n this._comparator = comparator;\n this.size = 0;\n}\n\nBinTree.prototype = new TreeBase();\n\n// returns true if inserted, false if duplicate\nBinTree.prototype.insert = function(data) {\n if(this._root === null) {\n // empty tree\n this._root = new Node(data);\n this.size++;\n return true;\n }\n\n var dir = 0;\n\n // setup\n var p = null; // parent\n var node = this._root;\n\n // search down\n while(true) {\n if(node === null) {\n // insert new node at the bottom\n node = new Node(data);\n p.set_child(dir, node);\n ret = true;\n this.size++;\n return true;\n }\n\n // stop if found\n if(this._comparator(node.data, data) === 0) {\n return false;\n }\n\n dir = this._comparator(node.data, data) < 0;\n\n // update helpers\n p = node;\n node = node.get_child(dir);\n }\n};\n\n// returns true if removed, false if not found\nBinTree.prototype.remove = function(data) {\n if(this._root === null) {\n return false;\n }\n\n var head = new Node(undefined); // fake tree root\n var node = head;\n node.right = this._root;\n var p = null; // parent\n var found = null; // found item\n var dir = 1;\n\n while(node.get_child(dir) !== null) {\n p = node;\n node = node.get_child(dir);\n var cmp = this._comparator(data, node.data);\n dir = cmp > 0;\n\n if(cmp === 0) {\n found = node;\n }\n }\n\n if(found !== null) {\n found.data = node.data;\n p.set_child(p.right === node, node.get_child(node.left === null));\n\n this._root = head.right;\n this.size--;\n return true;\n }\n else {\n return false;\n }\n};\n\nmodule.exports = BinTree;\n\n", "module.exports = {\n RBTree: require('./lib/rbtree'),\n BinTree: require('./lib/bintree')\n};\n", "//\n// TDigest:\n//\n// approximate distribution percentiles from a stream of reals\n//\nvar RBTree = require('bintrees').RBTree;\n\nfunction TDigest(delta, K, CX) {\n // allocate a TDigest structure.\n //\n // delta is the compression factor, the max fraction of mass that\n // can be owned by one centroid (bigger, up to 1.0, means more\n // compression). delta=false switches off TDigest behavior and treats\n // the distribution as discrete, with no merging and exact values\n // reported.\n //\n // K is a size threshold that triggers recompression as the TDigest\n // grows during input. (Set it to 0 to disable automatic recompression)\n //\n // CX specifies how often to update cached cumulative totals used\n // for quantile estimation during ingest (see cumulate()). Set to\n // 0 to use exact quantiles for each new point.\n //\n this.discrete = (delta === false);\n this.delta = delta || 0.01;\n this.K = (K === undefined) ? 25 : K;\n this.CX = (CX === undefined) ? 1.1 : CX;\n this.centroids = new RBTree(compare_centroid_means);\n this.nreset = 0;\n this.reset();\n}\n\nTDigest.prototype.reset = function() {\n // prepare to digest new points.\n //\n this.centroids.clear();\n this.n = 0;\n this.nreset += 1;\n this.last_cumulate = 0;\n};\n\nTDigest.prototype.size = function() {\n return this.centroids.size;\n};\n\nTDigest.prototype.toArray = function(everything) {\n // return {mean,n} of centroids as an array ordered by mean.\n //\n var result = [];\n if (everything) {\n this._cumulate(true); // be sure cumns are exact\n this.centroids.each(function(c) { result.push(c); });\n } else {\n this.centroids.each(function(c) { result.push({mean:c.mean, n:c.n}); });\n }\n return result;\n};\n\nTDigest.prototype.summary = function() {\n var approx = (this.discrete) ? \"exact \" : \"approximating \";\n var s = [approx + this.n + \" samples using \" + this.size() + \" centroids\",\n \"min = \"+this.percentile(0),\n \"Q1 = \"+this.percentile(0.25),\n \"Q2 = \"+this.percentile(0.5),\n \"Q3 = \"+this.percentile(0.75),\n \"max = \"+this.percentile(1.0)];\n return s.join('\\n');\n};\n\nfunction compare_centroid_means(a, b) {\n // order two centroids by mean.\n //\n return (a.mean > b.mean) ? 1 : (a.mean < b.mean) ? -1 : 0;\n}\n\nfunction compare_centroid_mean_cumns(a, b) {\n // order two centroids by mean_cumn.\n //\n return (a.mean_cumn - b.mean_cumn);\n}\n\nTDigest.prototype.push = function(x, n) {\n // incorporate value or array of values x, having count n into the\n // TDigest. n defaults to 1.\n //\n n = n || 1;\n x = Array.isArray(x) ? x : [x];\n for (var i = 0 ; i < x.length ; i++) {\n this._digest(x[i], n);\n }\n};\n\nTDigest.prototype.push_centroid = function(c) {\n // incorporate centroid or array of centroids c\n //\n c = Array.isArray(c) ? c : [c];\n for (var i = 0 ; i < c.length ; i++) {\n this._digest(c[i].mean, c[i].n);\n }\n};\n\nTDigest.prototype._cumulate = function(exact) {\n // update cumulative counts for each centroid\n //\n // exact: falsey means only cumulate after sufficient\n // growth. During ingest, these counts are used as quantile\n // estimates, and they work well even when somewhat out of\n // date. (this is a departure from the publication, you may set CX\n // to 0 to disable).\n //\n if (this.n === this.last_cumulate ||\n !exact && this.CX && this.CX > (this.n / this.last_cumulate)) {\n return;\n }\n var cumn = 0;\n this.centroids.each(function(c) {\n c.mean_cumn = cumn + c.n / 2; // half of n at the mean\n cumn = c.cumn = cumn + c.n;\n });\n this.n = this.last_cumulate = cumn;\n};\n\nTDigest.prototype.find_nearest = function(x) {\n // find the centroid closest to x. The assumption of\n // unique means and a unique nearest centroid departs from the\n // paper, see _digest() below\n //\n if (this.size() === 0) {\n return null;\n }\n var iter = this.centroids.lowerBound({mean:x}); // x <= iter || iter==null\n var c = (iter.data() === null) ? iter.prev() : iter.data();\n if (c.mean === x || this.discrete) {\n return c; // c is either x or a neighbor (discrete: no distance func)\n }\n var prev = iter.prev();\n if (prev && Math.abs(prev.mean - x) < Math.abs(c.mean - x)) {\n return prev;\n } else {\n return c;\n }\n};\n\nTDigest.prototype._new_centroid = function(x, n, cumn) {\n // create and insert a new centroid into the digest (don't update\n // cumulatives).\n //\n var c = {mean:x, n:n, cumn:cumn};\n this.centroids.insert(c);\n this.n += n;\n return c;\n};\n\nTDigest.prototype._addweight = function(nearest, x, n) {\n // add weight at location x to nearest centroid. adding x to\n // nearest will not shift its relative position in the tree and\n // require reinsertion.\n //\n if (x !== nearest.mean) {\n nearest.mean += n * (x - nearest.mean) / (nearest.n + n);\n }\n nearest.cumn += n;\n nearest.mean_cumn += n / 2;\n nearest.n += n;\n this.n += n;\n};\n\nTDigest.prototype._digest = function(x, n) {\n // incorporate value x, having count n into the TDigest.\n //\n var min = this.centroids.min();\n var max = this.centroids.max();\n var nearest = this.find_nearest(x);\n if (nearest && nearest.mean === x) {\n // accumulate exact matches into the centroid without\n // limit. this is a departure from the paper, made so\n // centroids remain unique and code can be simple.\n this._addweight(nearest, x, n);\n } else if (nearest === min) {\n this._new_centroid(x, n, 0); // new point around min boundary\n } else if (nearest === max ) {\n this._new_centroid(x, n, this.n); // new point around max boundary\n } else if (this.discrete) {\n this._new_centroid(x, n, nearest.cumn); // never merge\n } else {\n // conider a merge based on nearest centroid's capacity. if\n // there's not room for all of n, don't bother merging any of\n // it into nearest, as we'll have to make a new centroid\n // anyway for the remainder (departure from the paper).\n var p = nearest.mean_cumn / this.n;\n var max_n = Math.floor(4 * this.n * this.delta * p * (1 - p));\n if (max_n - nearest.n >= n) {\n this._addweight(nearest, x, n);\n } else {\n this._new_centroid(x, n, nearest.cumn);\n }\n }\n this._cumulate(false);\n if (!this.discrete && this.K && this.size() > this.K / this.delta) {\n // re-process the centroids and hope for some compression.\n this.compress();\n }\n};\n\nTDigest.prototype.bound_mean = function(x) {\n // find centroids lower and upper such that lower.mean < x <\n // upper.mean or lower.mean === x === upper.mean. Don't call\n // this for x out of bounds.\n //\n var iter = this.centroids.upperBound({mean:x}); // x < iter\n var lower = iter.prev(); // lower <= x\n var upper = (lower.mean === x) ? lower : iter.next();\n return [lower, upper];\n};\n\nTDigest.prototype.p_rank = function(x_or_xlist) {\n // return approximate percentile-ranks (0..1) for data value x.\n // or list of x. calculated according to\n // https://en.wikipedia.org/wiki/Percentile_rank\n //\n // (Note that in continuous mode, boundary sample values will\n // report half their centroid weight inward from 0/1 as the\n // percentile-rank. X values outside the observed range return\n // 0/1)\n //\n // this triggers cumulate() if cumn's are out of date.\n //\n var xs = Array.isArray(x_or_xlist) ? x_or_xlist : [x_or_xlist];\n var ps = xs.map(this._p_rank, this);\n return Array.isArray(x_or_xlist) ? ps : ps[0];\n};\n\nTDigest.prototype._p_rank = function(x) {\n if (this.size() === 0) {\n return undefined;\n } else if (x < this.centroids.min().mean) {\n return 0.0;\n } else if (x > this.centroids.max().mean) {\n return 1.0;\n }\n // find centroids that bracket x and interpolate x's cumn from\n // their cumn's.\n this._cumulate(true); // be sure cumns are exact\n var bound = this.bound_mean(x);\n var lower = bound[0], upper = bound[1];\n if (this.discrete) {\n return lower.cumn / this.n;\n } else {\n var cumn = lower.mean_cumn;\n if (lower !== upper) {\n cumn += (x - lower.mean) * (upper.mean_cumn - lower.mean_cumn) / (upper.mean - lower.mean);\n }\n return cumn / this.n;\n }\n};\n\nTDigest.prototype.bound_mean_cumn = function(cumn) {\n // find centroids lower and upper such that lower.mean_cumn < x <\n // upper.mean_cumn or lower.mean_cumn === x === upper.mean_cumn. Don't call\n // this for cumn out of bounds.\n //\n // XXX because mean and mean_cumn give rise to the same sort order\n // (up to identical means), use the mean rbtree for our search.\n this.centroids._comparator = compare_centroid_mean_cumns;\n var iter = this.centroids.upperBound({mean_cumn:cumn}); // cumn < iter\n this.centroids._comparator = compare_centroid_means;\n var lower = iter.prev(); // lower <= cumn\n var upper = (lower && lower.mean_cumn === cumn) ? lower : iter.next();\n return [lower, upper];\n};\n\nTDigest.prototype.percentile = function(p_or_plist) {\n // for percentage p (0..1), or for each p in a list of ps, return\n // the smallest data value q at which at least p percent of the\n // observations <= q.\n //\n // for discrete distributions, this selects q using the Nearest\n // Rank Method\n // (https://en.wikipedia.org/wiki/Percentile#The_Nearest_Rank_method)\n // (in scipy, same as percentile(...., interpolation='higher')\n //\n // for continuous distributions, interpolates data values between\n // count-weighted bracketing means.\n //\n // this triggers cumulate() if cumn's are out of date.\n //\n var ps = Array.isArray(p_or_plist) ? p_or_plist : [p_or_plist];\n var qs = ps.map(this._percentile, this);\n return Array.isArray(p_or_plist) ? qs : qs[0];\n};\n\nTDigest.prototype._percentile = function(p) {\n if (this.size() === 0) {\n return undefined;\n }\n this._cumulate(true); // be sure cumns are exact\n var h = this.n * p;\n var bound = this.bound_mean_cumn(h);\n var lower = bound[0], upper = bound[1];\n\n if (upper === lower || lower === null || upper === null) {\n return (lower || upper).mean;\n } else if (!this.discrete) {\n return lower.mean + (h - lower.mean_cumn) * (upper.mean - lower.mean) / (upper.mean_cumn - lower.mean_cumn);\n } else if (h <= lower.cumn) {\n return lower.mean;\n } else {\n return upper.mean;\n }\n};\n\nfunction pop_random(choices) {\n // remove and return an item randomly chosen from the array of choices\n // (mutates choices)\n //\n var idx = Math.floor(Math.random() * choices.length);\n return choices.splice(idx, 1)[0];\n}\n\nTDigest.prototype.compress = function() {\n // TDigests experience worst case compression (none) when input\n // increases monotonically. Improve on any bad luck by\n // reconsuming digest centroids as if they were weighted points\n // while shuffling their order (and hope for the best).\n //\n if (this.compressing) {\n return;\n }\n var points = this.toArray();\n this.reset();\n this.compressing = true;\n while (points.length > 0) {\n this.push_centroid(pop_random(points));\n }\n this._cumulate(true);\n this.compressing = false;\n};\n\nfunction Digest(config) {\n // allocate a distribution digest structure. This is an extension\n // of a TDigest structure that starts in exact histogram (discrete)\n // mode, and automatically switches to TDigest mode for large\n // samples that appear to be from a continuous distribution.\n //\n this.config = config || {};\n this.mode = this.config.mode || 'auto'; // disc, cont, auto\n TDigest.call(this, this.mode === 'cont' ? config.delta : false);\n this.digest_ratio = this.config.ratio || 0.9;\n this.digest_thresh = this.config.thresh || 1000;\n this.n_unique = 0;\n}\nDigest.prototype = Object.create(TDigest.prototype);\nDigest.prototype.constructor = Digest;\n\nDigest.prototype.push = function(x_or_xlist) {\n TDigest.prototype.push.call(this, x_or_xlist);\n this.check_continuous();\n};\n\nDigest.prototype._new_centroid = function(x, n, cumn) {\n this.n_unique += 1;\n TDigest.prototype._new_centroid.call(this, x, n, cumn);\n};\n\nDigest.prototype._addweight = function(nearest, x, n) {\n if (nearest.n === 1) {\n this.n_unique -= 1;\n }\n TDigest.prototype._addweight.call(this, nearest, x, n);\n};\n\nDigest.prototype.check_continuous = function() {\n // while in 'auto' mode, if there are many unique elements, assume\n // they are from a continuous distribution and switch to 'cont'\n // mode (tdigest behavior). Return true on transition from\n // disctete to continuous.\n if (this.mode !== 'auto' || this.size() < this.digest_thresh) {\n return false;\n }\n if (this.n_unique / this.size() > this.digest_ratio) {\n this.mode = 'cont';\n this.discrete = false;\n this.delta = this.config.delta || 0.01;\n this.compress();\n return true;\n }\n return false;\n};\n\nmodule.exports = {\n 'TDigest': TDigest,\n 'Digest': Digest\n};\n", "/**\n * @packageDocumentation\n *\n * Stores metrics in memory and periodically invokes a configured callback to\n * receive them.\n *\n * @example\n *\n * ```ts\n * import { createLibp2p } from 'libp2p'\n * import { simpleMetrics } from '@libp2p/simple-metrics'\n *\n * const node = await createLibp2p({\n * // ... other options\n * metrics: simpleMetrics({\n * onMetrics: (metrics) => {\n * // do something with metrics\n * }\n * }),\n * intervalMs: 1000 // default 1s\n * })\n *\n * ```\n */\n\nimport { serviceCapabilities } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport { TDigest } from 'tdigest'\nimport type { Startable, MultiaddrConnection, Stream, Metric, MetricGroup, StopTimer, Metrics, CalculatedMetricOptions, MetricOptions, Counter, CounterGroup, CalculateMetric, Histogram, HistogramOptions, HistogramGroup, Summary, SummaryOptions, SummaryGroup, CalculatedHistogramOptions, CalculatedSummaryOptions, ComponentLogger, Logger, MessageStream } from '@libp2p/interface'\n\nconst log = logger('libp2p:simple-metrics')\n\nclass SimpleMetric implements Metric {\n private value: number = 0\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedMetricOptions) {\n this.calculate = opts?.calculate\n }\n\n async collect (): Promise<number> {\n if (this.calculate != null) {\n return this.calculate()\n }\n\n return this.value\n }\n\n update (value: number): void {\n this.value = value\n }\n\n increment (value: number = 1): void {\n this.value += value\n }\n\n decrement (value: number = 1): void {\n this.value -= value\n }\n\n reset (): void {\n this.value = 0\n }\n\n timer (): StopTimer {\n const start = Date.now()\n\n return () => {\n this.value = Date.now() - start\n }\n }\n}\n\nclass SimpleGroupMetric implements MetricGroup {\n private values: Record<string, number> = {}\n private readonly calculate?: CalculateMetric<Record<string, number>>\n\n constructor (opts?: CalculatedMetricOptions<Record<string, number>>) {\n this.calculate = opts?.calculate\n }\n\n async collect (): Promise<Record<string, number>> {\n if (this.calculate != null) {\n return this.calculate()\n }\n\n return this.values\n }\n\n update (values: Record<string, number>): void {\n Object.entries(values).forEach(([key, value]) => {\n this.values[key] = value\n })\n }\n\n increment (values: Record<string, number | unknown>): void {\n Object.entries(values).forEach(([key, value]) => {\n this.values[key] = this.values[key] ?? 0\n const inc = typeof value === 'number' ? value : 1\n\n this.values[key] += Number(inc)\n })\n }\n\n decrement (values: Record<string, number | unknown>): void {\n Object.entries(values).forEach(([key, value]) => {\n this.values[key] = this.values[key] ?? 0\n const dec = typeof value === 'number' ? value : 1\n\n this.values[key] -= Number(dec)\n })\n }\n\n reset (): void {\n this.values = {}\n }\n\n timer (key: string): StopTimer {\n const start = Date.now()\n\n return () => {\n this.values[key] = Date.now() - start\n }\n }\n}\n\nclass SimpleHistogram implements Histogram {\n private bucketValues = new Map<number, number>()\n private countValue: number = 0\n private sumValue: number = 0\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedHistogramOptions) {\n const buckets = [\n ...(opts?.buckets ?? [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]),\n Infinity\n ]\n for (const bucket of buckets) {\n this.bucketValues.set(bucket, 0)\n }\n this.calculate = opts?.calculate\n }\n\n public async collect (): Promise<{ count: number, sum: number, buckets: Record<number, number> }> {\n if (this.calculate != null) {\n this.observe(await this.calculate())\n }\n\n return {\n count: this.countValue,\n sum: this.sumValue,\n buckets: { ...this.bucketValues }\n }\n }\n\n observe (value: number): void {\n this.countValue++\n this.sumValue += value\n\n for (const [bucket, count] of this.bucketValues.entries()) {\n if (value <= bucket) {\n this.bucketValues.set(bucket, count + 1)\n }\n }\n }\n\n reset (): void {\n this.countValue = 0\n this.sumValue = 0\n for (const bucket of this.bucketValues.keys()) {\n this.bucketValues.set(bucket, 0)\n }\n }\n\n timer (): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe(Date.now() - start)\n }\n }\n}\n\nclass SimpleHistogramGroup implements HistogramGroup {\n public histograms: Record<string, SimpleHistogram> = {}\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedHistogramOptions) {\n this.histograms = {}\n this.calculate = opts?.calculate\n }\n\n public async collect (): Promise<Record<string, { count: number, sum: number, buckets: Record<number, number> }>> {\n const output: Record<string, { count: number, sum: number, buckets: Record<number, number> }> = {}\n\n for (const [key, histogram] of Object.entries(this.histograms)) {\n output[key] = await histogram.collect()\n }\n\n return output\n }\n\n observe (values: Partial<Record<string, number>>): void {\n for (const [key, value] of Object.entries(values) as Array<[string, number]>) {\n if (this.histograms[key] === undefined) {\n this.histograms[key] = new SimpleHistogram()\n }\n\n this.histograms[key].observe(value)\n }\n }\n\n reset (): void {\n for (const histogram of Object.values(this.histograms)) {\n histogram.reset()\n }\n }\n\n timer (key: string): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe({ [key]: Date.now() - start })\n }\n }\n}\n\nclass SimpleSummary implements Summary {\n public sumValue: number = 0\n public countValue: number = 0\n public percentiles: number[]\n public tdigest = new TDigest(0.01)\n private readonly compressCount: number\n private readonly calculate?: CalculateMetric\n\n constructor (opts?: CalculatedSummaryOptions) {\n this.percentiles = opts?.percentiles ?? [0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999]\n this.compressCount = opts?.compressCount ?? 1000\n this.calculate = opts?.calculate\n }\n\n public async collect (): Promise<{ count: number, sum: number, percentiles: Record<string, number> }> {\n if (this.calculate != null) {\n this.observe(await this.calculate())\n }\n\n return {\n count: this.countValue,\n sum: this.sumValue,\n percentiles: Object.fromEntries(this.percentiles.map(p => [p, this.tdigest.percentile(p)]))\n }\n }\n\n observe (value: number): void {\n this.sumValue += value\n this.countValue++\n\n this.tdigest.push(value)\n if (this.tdigest.size() > this.compressCount) {\n this.tdigest.compress()\n }\n }\n\n reset (): void {\n this.sumValue = 0\n this.countValue = 0\n\n this.tdigest.reset()\n }\n\n timer (): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe(Date.now() - start)\n }\n }\n}\n\nclass SimpleSummaryGroup implements SummaryGroup {\n public summaries: Record<string, SimpleSummary> = {}\n private readonly opts?: CalculatedSummaryOptions\n\n constructor (opts?: CalculatedSummaryOptions) {\n this.summaries = {}\n this.opts = opts\n }\n\n public async collect (): Promise<Record<string, { count: number, sum: number, percentiles: Record<string, number> }>> {\n return {\n ...Object.fromEntries(Object.entries(this.summaries).map(([key, summary]) => {\n return [key, {\n count: summary.countValue,\n sum: summary.sumValue,\n percentiles: Object.fromEntries(summary.percentiles.map(p => [p, summary.tdigest.percentile(p)]))\n }]\n }))\n }\n }\n\n observe (values: Record<string, number>): void {\n for (const [key, value] of Object.entries(values)) {\n if (this.summaries[key] === undefined) {\n this.summaries[key] = new SimpleSummary(this.opts)\n }\n\n this.summaries[key].observe(value)\n }\n }\n\n reset (): void {\n for (const summary of Object.values(this.summaries)) {\n summary.reset()\n }\n }\n\n timer (key: string): StopTimer {\n const start = Date.now()\n\n return () => {\n this.observe({ [key]: Date.now() - start })\n }\n }\n}\n\nexport interface OnMetrics { (metrics: Record<string, any>): void }\n\nexport interface SimpleMetricsInit {\n /**\n * How often to invoke the onMetrics callback\n */\n intervalMs?: number\n\n /**\n * A callback periodically invoked with collected metrics\n */\n onMetrics: OnMetrics\n}\n\nexport interface SimpleMetricsComponents {\n logger: ComponentLogger\n}\n\nclass SimpleMetrics implements Metrics, Startable {\n public metrics = new Map<string, SimpleMetric | SimpleGroupMetric | SimpleHistogram | SimpleHistogramGroup | SimpleSummary | SimpleSummaryGroup>()\n private readonly transferStats: Map<string, number>\n private started: boolean\n private interval?: ReturnType<typeof setInterval>\n private readonly intervalMs: number\n private readonly onMetrics: OnMetrics\n private readonly log: Logger\n\n constructor (components: SimpleMetricsComponents, init: SimpleMetricsInit) {\n this.log = components.logger.forComponent('libp2p:simple-metrics')\n this.started = false\n\n this._emitMetrics = this._emitMetrics.bind(this)\n\n this.intervalMs = init.intervalMs ?? 1000\n this.onMetrics = init.onMetrics\n\n // holds global and per-protocol sent/received stats\n this.transferStats = new Map()\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/metrics-simple'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/metrics'\n ]\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n\n this.interval = setInterval(this._emitMetrics, this.intervalMs)\n }\n\n stop (): void {\n this.started = false\n\n clearInterval(this.interval)\n this.transferStats.clear()\n }\n\n private _emitMetrics (): void {\n Promise.resolve().then(async () => {\n const output: Record<string, any> = {}\n\n for (const [name, metric] of this.metrics.entries()) {\n output[name] = await metric.collect()\n }\n\n this.onMetrics(structuredClone(output))\n })\n .catch(err => {\n log.error('could not invoke onMetrics callback - %e', err)\n })\n }\n\n /**\n * Increment the transfer stat for the passed key, making sure\n * it exists first\n */\n _incrementValue (key: string, value: number): void {\n const existing = this.transferStats.get(key) ?? 0\n\n this.transferStats.set(key, existing + value)\n }\n\n /**\n * Override the sink/source of the stream to count the bytes\n * in and out\n */\n _track (stream: MessageStream, name: string): void {\n stream.addEventListener('message', (evt) => {\n this._incrementValue(`${name} received`, evt.data.byteLength)\n })\n\n const send = stream.send.bind(stream)\n stream.send = (buf) => {\n this._incrementValue(`${name} sent`, buf.byteLength)\n\n return send(buf)\n }\n }\n\n trackMultiaddrConnection (maConn: MultiaddrConnection): void {\n this._track(maConn, 'global')\n }\n\n trackProtocolStream (stream: Stream): void {\n if (stream.protocol == null) {\n // protocol not negotiated yet, should not happen as the upgrader\n // calls this handler after protocol negotiation\n return\n }\n\n this._track(stream, stream.protocol)\n }\n\n registerMetric (name: string, opts: CalculatedMetricOptions): void\n registerMetric (name: string, opts?: MetricOptions): Metric\n registerMetric (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerMetricGroup (name: string, opts: CalculatedMetricOptions<Record<string, number>>): void\n registerMetricGroup (name: string, opts?: MetricOptions): MetricGroup\n registerMetricGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleGroupMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerCounter (name: string, opts: CalculatedMetricOptions): void\n registerCounter (name: string, opts?: MetricOptions): Counter\n registerCounter (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerCounterGroup (name: string, opts: CalculatedMetricOptions<Record<string, number>>): void\n registerCounterGroup (name: string, opts?: MetricOptions): CounterGroup\n registerCounterGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleGroupMetric(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerHistogram (name: string, opts: CalculatedHistogramOptions): void\n registerHistogram (name: string, opts?: HistogramOptions): Histogram\n registerHistogram (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleHistogram(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerHistogramGroup (name: string, opts: CalculatedHistogramOptions<Record<string, number>>): void\n registerHistogramGroup (name: string, opts?: HistogramOptions): HistogramGroup\n registerHistogramGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleHistogramGroup(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerSummary (name: string, opts: CalculatedSummaryOptions): void\n registerSummary (name: string, opts?: SummaryOptions): Summary\n registerSummary (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleSummary(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n registerSummaryGroup (name: string, opts: CalculatedSummaryOptions<Record<string, number>>): void\n registerSummaryGroup (name: string, opts?: SummaryOptions): SummaryGroup\n registerSummaryGroup (name: string, opts: any = {}): any {\n if (name == null || name.trim() === '') {\n throw new Error('Metric name is required')\n }\n\n let metric = this.metrics.get(name)\n\n if (metric != null) {\n this.log('reuse existing metric', name)\n return metric\n }\n\n metric = new SimpleSummaryGroup(opts)\n this.metrics.set(name, metric)\n\n return metric\n }\n\n createTrace (): any {\n // no-op\n }\n\n traceFunction <T extends (...args: any[]) => any> (name: string, fn: T): T {\n // no-op\n return fn\n }\n}\n\nexport function simpleMetrics (init: SimpleMetricsInit): (components: SimpleMetricsComponents) => Metrics {\n return (components) => new SimpleMetrics(components, init)\n}\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.js'\nimport type { Stream } from './stream.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './connection-protector.js'\nexport * from './content-routing.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './keys.js'\nexport * from './message-stream.js'\nexport * from './metrics.js'\nexport * from './multiaddr-connection.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './record.js'\nexport * from './startable.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './stream.js'\nexport * from './topology.js'\nexport * from './transport.js'\n\nexport * from 'main-event'\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { return new Uint8Array(o) }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "const s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nconst mo = y / 12;\n\ntype Years = 'years' | 'year' | 'yrs' | 'yr' | 'y';\ntype Months = 'months' | 'month' | 'mo';\ntype Weeks = 'weeks' | 'week' | 'w';\ntype Days = 'days' | 'day' | 'd';\ntype Hours = 'hours' | 'hour' | 'hrs' | 'hr' | 'h';\ntype Minutes = 'minutes' | 'minute' | 'mins' | 'min' | 'm';\ntype Seconds = 'seconds' | 'second' | 'secs' | 'sec' | 's';\ntype Milliseconds = 'milliseconds' | 'millisecond' | 'msecs' | 'msec' | 'ms';\ntype Unit =\n | Years\n | Months\n | Weeks\n | Days\n | Hours\n | Minutes\n | Seconds\n | Milliseconds;\n\ntype UnitAnyCase = Capitalize<Unit> | Uppercase<Unit> | Unit;\n\nexport type StringValue =\n | `${number}`\n | `${number}${UnitAnyCase}`\n | `${number} ${UnitAnyCase}`;\n\ninterface Options {\n /**\n * Set to `true` to use verbose formatting. Defaults to `false`.\n */\n long?: boolean;\n}\n\n/**\n * Parse or format the given value.\n *\n * @param value - The string or number to convert\n * @param options - Options for the conversion\n * @throws Error if `value` is not a non-empty string or a number\n */\nexport function ms(value: StringValue, options?: Options): number;\nexport function ms(value: number, options?: Options): string;\nexport function ms(\n value: StringValue | number,\n options?: Options,\n): number | string {\n if (typeof value === 'string') {\n return parse(value);\n } else if (typeof value === 'number') {\n return format(value, options);\n }\n throw new Error(\n `Value provided to ms() must be a string or number. value=${JSON.stringify(value)}`,\n );\n}\n\nexport default ms;\n\n/**\n * Parse the given string and return milliseconds.\n *\n * @param str - A string to parse to milliseconds\n * @returns The parsed value in milliseconds, or `NaN` if the string can't be\n * parsed\n */\nexport function parse(str: string): number {\n if (typeof str !== 'string' || str.length === 0 || str.length > 100) {\n throw new Error(\n `Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(str)}`,\n );\n }\n const match =\n /^(?<value>-?\\d*\\.?\\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(\n str,\n );\n\n if (!match?.groups) {\n return NaN;\n }\n\n // Named capture groups need to be manually typed today.\n // https://github.com/microsoft/TypeScript/issues/32098\n const { value, unit = 'ms' } = match.groups as {\n value: string;\n unit: string | undefined;\n };\n\n const n = parseFloat(value);\n\n const matchUnit = unit.toLowerCase() as Lowercase<Unit>;\n\n /* istanbul ignore next - istanbul doesn't understand, but thankfully the TypeScript the exhaustiveness check in the default case keeps us type safe here */\n switch (matchUnit) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'months':\n case 'month':\n case 'mo':\n return n * mo;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n matchUnit satisfies never;\n throw new Error(\n `Unknown unit \"${matchUnit}\" provided to ms.parse(). value=${JSON.stringify(str)}`,\n );\n }\n}\n\n/**\n * Parse the given StringValue and return milliseconds.\n *\n * @param value - A typesafe StringValue to parse to milliseconds\n * @returns The parsed value in milliseconds, or `NaN` if the string can't be\n * parsed\n */\nexport function parseStrict(value: StringValue): number {\n return parse(value);\n}\n\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms: number): StringValue {\n const msAbs = Math.abs(ms);\n if (msAbs >= y) {\n return `${Math.round(ms / y)}y`;\n }\n if (msAbs >= mo) {\n return `${Math.round(ms / mo)}mo`;\n }\n if (msAbs >= w) {\n return `${Math.round(ms / w)}w`;\n }\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms: number): StringValue {\n const msAbs = Math.abs(ms);\n if (msAbs >= y) {\n return plural(ms, msAbs, y, 'year');\n }\n if (msAbs >= mo) {\n return plural(ms, msAbs, mo, 'month');\n }\n if (msAbs >= w) {\n return plural(ms, msAbs, w, 'week');\n }\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n\n/**\n * Format the given integer as a string.\n *\n * @param ms - milliseconds\n * @param options - Options for the conversion\n * @returns The formatted string\n */\nexport function format(ms: number, options?: Options): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) {\n throw new Error('Value provided to ms.format() must be of type number.');\n }\n\n return options?.long ? fmtLong(ms) : fmtShort(ms);\n}\n\n/**\n * Pluralization helper.\n */\nfunction plural(\n ms: number,\n msAbs: number,\n n: number,\n name: string,\n): StringValue {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}` as StringValue;\n}\n", "/* eslint-disable no-console */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms'\nimport type { Debug, Debugger, Options } from './index.js'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string, options?: Options): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n if (options?.onLog != null) {\n options.onLog(...args)\n } else {\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms'\nimport setup from './common.js'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.js'\nimport type ms from 'ms'\n\nexport interface Options {\n /**\n * Receives log lines. The default transport writes the log line to\n * `process.stderr`, `console.debug` or `console.log` depending on what is\n * available in the environment.\n *\n * The args are not formatted - they can be passed to `util.format` from\n * Node.js or to `format` exported from this module as `weald/format`.\n *\n * @example Receiving log lines\n *\n * ```ts\n * import debug from 'weald'\n * import { format } from 'weald/format'\n *\n * const logger = debug('my-namespace', {\n * onLog (...args: any[]) {\n * const line = format(...args)\n * // do something with `line`\n * }\n * })\n * ```\n */\n onLog?(...args: any[]): void\n}\n\nexport interface Debug {\n (namespace: string, options?: Options): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(...args: any[]): any\n selectColor(namespace: string): string | number\n humanize: typeof ms\n useColors(): boolean\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(...args: any[]): any\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n useColors(): boolean\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %e', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId, Logger, ComponentLogger } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\nimport type { Options as LoggerOptions } from 'weald'\n\nexport type { LoggerOptions }\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nfunction formatError (v: Error): string {\n const message = notEmpty(v.message)\n const stack = notEmpty(v.stack)\n\n // some browser errors (mostly from Firefox) have no message or no stack,\n // sometimes both, sometimes neither. Sometimes the message is in the stack,\n // sometimes is isn't so try to do *something* useful\n if (message != null && stack != null) {\n if (stack.includes(message)) {\n return stack\n }\n\n return `${message}\\n${stack}`\n }\n\n if (stack != null) {\n return stack\n }\n\n if (message != null) {\n return message\n }\n\n return v.toString()\n}\n\nfunction isAggregateError (err?: any): err is AggregateError {\n return err?.name === 'AggregateError'\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n if (v == null) {\n return 'undefined'\n }\n\n if (isAggregateError(v)) {\n const indent = ' '\n\n let output = formatError(v)\n\n if (v.errors.length > 0) {\n output += `\\n${indent}${\n v.errors.map(err => ` ${formatError(err).split('\\n').join(`\\n${indent}`)}`).join(`\\n${indent}`)\n }`\n } else {\n output += `\\n${indent}[Error list was empty]`\n }\n\n return output.trim()\n }\n\n return formatError(v)\n}\n\nexport type { Logger, ComponentLogger }\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions extends LoggerOptions {\n prefixLength?: number\n suffixLength?: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: PeerLoggerOptions = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options), options)\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string, options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`, options)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name, options)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string, options?: LoggerOptions): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`, options)\n }\n\n return Object.assign(debug(name, options), {\n error: debug(`${name}:error`, options),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`, options)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n"],
|
|
5
|
+
"mappings": ";kqBAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,CACA,SAASC,GAAW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AAI,EAElC,OAAIC,GAAU,MACZ,KAAK,IAAI,wBAAyBD,CAAI,EAC/BC,IAGTA,EAAS,IAAIP,GAAmBjB,CAAI,EACpC,KAAK,QAAQ,IAAIuB,EAAMC,CAAM,EAEtBA,EACT,CAEA,aAAW,CAEX,CAEA,cAAmDD,EAAcS,EAAK,CAEpE,OAAOA,CACT,GAGI,SAAUC,GAAeZ,EAAuB,CACpD,OAAQD,GAAe,IAAID,GAAcC,EAAYC,CAAI,CAC3D",
|
|
6
|
+
"names": ["require_treebase", "__commonJSMin", "exports", "module", "TreeBase", "data", "res", "c", "iter", "item", "cur", "cmp", "i", "Iterator", "cb", "it", "tree", "root", "save", "start", "require_rbtree", "__commonJSMin", "exports", "module", "TreeBase", "Node", "data", "dir", "val", "RBTree", "comparator", "ret", "head", "last", "gp", "ggp", "p", "node", "is_red", "dir2", "single_rotate", "double_rotate", "cmp", "found", "sr", "sibling", "gpc", "root", "save", "require_bintree", "__commonJSMin", "exports", "module", "TreeBase", "Node", "data", "dir", "val", "BinTree", "comparator", "p", "node", "head", "found", "cmp", "require_bintrees", "__commonJSMin", "exports", "module", "require_tdigest", "__commonJSMin", "exports", "module", "RBTree", "TDigest", "delta", "K", "CX", "compare_centroid_means", "everything", "result", "c", "approx", "s", "a", "b", "compare_centroid_mean_cumns", "x", "n", "i", "exact", "cumn", "iter", "prev", "nearest", "min", "max", "p", "max_n", "lower", "upper", "x_or_xlist", "xs", "ps", "bound", "p_or_plist", "qs", "h", "pop_random", "choices", "idx", "points", "Digest", "config", "index_exports", "__export", "simpleMetrics", "serviceCapabilities", "serviceDependencies", "empty", "coerce", "o", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base58btc", "baseX", "base58flickr", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "s", "value: StringValue | number", "options?: Options", "e", "l", "p", "t", "c", "str: string", "u", "d", "f", "d", "ms: number", "c", "ms", "f", "m", "p", "options?: Options", "t", "msAbs: number", "n: number", "name: string", "n", "r", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "c", "destroy", "key", "selectColor", "namespace", "hash", "i", "options", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "storage", "localstorage", "colors", "useColors", "formatArgs", "args", "c", "index", "lastC", "match", "log", "save", "namespaces", "load", "r", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "src_default", "v", "base58btc", "base32", "base64", "formatError", "message", "notEmpty", "stack", "isAggregateError", "err", "indent", "output", "createDisabledLogger", "namespace", "logger", "logger", "name", "options", "trace", "createDisabledLogger", "src_default", "r", "scope", "notEmpty", "str", "import_tdigest", "log", "logger", "SimpleMetric", "opts", "value", "start", "SimpleGroupMetric", "values", "key", "inc", "dec", "SimpleHistogram", "buckets", "bucket", "count", "SimpleHistogramGroup", "output", "histogram", "SimpleSummary", "p", "SimpleSummaryGroup", "summary", "SimpleMetrics", "components", "init", "serviceCapabilities", "name", "metric", "err", "existing", "stream", "evt", "send", "buf", "maConn", "fn", "simpleMetrics"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@libp2p/simple-metrics",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.6",
|
|
4
4
|
"description": "Simple in-memory metrics gathering for libp2p",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/metrics-simple#readme",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@libp2p/interface": "^3.0.2",
|
|
46
|
-
"@libp2p/logger": "^6.0
|
|
46
|
+
"@libp2p/logger": "^6.1.0",
|
|
47
47
|
"tdigest": "^0.1.2"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|