@libp2p/ping 3.0.10 → 3.0.11-19796b103
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 +1 -1
- package/dist/index.min.js.map +3 -3
- package/package.json +6 -6
- package/dist/typedoc-urls.json +0 -11
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PPing = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PPing=(()=>{var I=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var Y=(o,t)=>{for(var e in t)I(o,e,{get:t[e],enumerable:!0})},K=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of X(t))!q.call(o,n)&&n!==e&&I(o,n,{get:()=>t[n],enumerable:!(r=G(t,n))||r.enumerable});return o};var z=o=>K(I({},"__esModule",{value:!0}),o);var nt={};Y(nt,{PING_PROTOCOL:()=>_,ping:()=>rt});var b=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var g=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}},w=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var S=Symbol.for("@libp2p/service-capabilities"),it=Symbol.for("@libp2p/service-dependencies");function x(o,t){if(o===t)return!0;if(o.byteLength!==t.byteLength)return!1;for(let e=0;e<o.byteLength;e++)if(o[e]!==t[e])return!1;return!0}function p(o=0){return new Uint8Array(o)}function d(o=0){return new Uint8Array(o)}function A(o,t){t==null&&(t=o.reduce((n,s)=>n+s.length,0));let e=d(t),r=0;for(let n of o)e.set(n,r),r+=n.length;return e}var D=Symbol.for("@achingbrain/uint8arraylist");function N(o,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let r of o){let n=e+r.byteLength;if(t<n)return{buf:r,index:t-e};e=n}throw new RangeError("index is out of bounds")}function y(o){return!!o?.[D]}var E=class o{bufs;length;[D]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else if(y(r))e+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else if(y(r))e+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=N(this.bufs,t);return e.buf[e.index]}set(t,e){let r=N(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else if(y(t))for(let r=0;r<t.length;r++)this.set(e+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:r,length:n}=this._subList(t,e);return A(r,n)}subarray(t,e){let{bufs:r,length:n}=this._subList(t,e);return r.length===1?r[0]:A(r,n)}sublist(t,e){let{bufs:r,length:n}=this._subList(t,e),s=new o;return s.length=n,s.bufs=[...r],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let s=0;s<this.bufs.length;s++){let a=this.bufs[s],u=n,f=u+a.byteLength;if(n=f,t>=f)continue;let m=t>=u&&t<f,l=e>u&&e<=f;if(m&&l){if(t===u&&e===f){r.push(a);break}let i=t-u;r.push(a.subarray(i,i+(e-t)));break}if(m){if(t===0){r.push(a);continue}r.push(a.subarray(t-u));continue}if(l){if(e===f){r.push(a);break}r.push(a.subarray(0,e-u));break}r.push(a)}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!y(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let s=256,a=new Int32Array(s);for(let i=0;i<s;i++)a[i]=-1;for(let i=0;i<n;i++)a[r[i]]=i;let u=a,f=this.byteLength-r.byteLength,m=r.byteLength-1,l;for(let i=e;i<=f;i+=l){l=0;for(let h=m;h>=0;h--){let c=this.get(i+h);if(r[h]!==c){l=Math.max(1,h-u[c]);break}}if(l===0)return i}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let r=d(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){let n=p(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let r=d(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){let n=p(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(t==null||!(t instanceof o)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!x(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let r=new o;return r.bufs=t,e==null&&(e=t.reduce((n,s)=>n+s.byteLength,0)),r.length=e,r}};function V(o=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(o))}function L(o){if(isNaN(o)||o<=0)throw new b("random bytes length must be a Number bigger than 0");return V(o)}var O=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},T=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},C=o=>globalThis.DOMException===void 0?new T(o):new DOMException(o),B=o=>{let t=o.reason===void 0?C("This operation was aborted."):o.reason;return t instanceof Error?t:C(t)};function U(o,t){let{milliseconds:e,fallback:r,message:n,customTimers:s={setTimeout,clearTimeout}}=t,a,u,m=new Promise((l,i)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:c}=t;c.aborted&&i(B(c)),u=()=>{i(B(c))},c.addEventListener("abort",u,{once:!0})}if(e===Number.POSITIVE_INFINITY){o.then(l,i);return}let h=new O;a=s.setTimeout.call(void 0,()=>{if(r){try{l(r())}catch(c){i(c)}return}typeof o.cancel=="function"&&o.cancel(),n===!1?l():n instanceof Error?i(n):(h.message=n??`Promise timed out after ${e} milliseconds`,i(h))},e),(async()=>{try{l(await o)}catch(c){i(c)}})()}).finally(()=>{m.clear(),u&&t.signal&&t.signal.removeEventListener("abort",u)});return m.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},m}var Q=o=>{let t=o.addEventListener||o.on||o.addListener,e=o.removeEventListener||o.off||o.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(o),removeListener:e.bind(o)}};function J(o,t,e){let r,n=new Promise((s,a)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let u=[t].flat(),f=[],{addListener:m,removeListener:l}=Q(o),i=async(...c)=>{let P=e.multiArgs?c:c[0];if(e.filter)try{if(!await e.filter(P))return}catch($){r(),a($);return}f.push(P),e.count===f.length&&(r(),s(f))},h=(...c)=>{r(),a(e.rejectionMultiArgs?c:c[0])};r=()=>{for(let c of u)l(c,i);for(let c of e.rejectionEvents)u.includes(c)||l(c,h)};for(let c of u)m(c,i);for(let c of e.rejectionEvents)u.includes(c)||m(c,h);e.signal&&e.signal.addEventListener("abort",()=>{h(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(f)});if(n.cancel=r,typeof e.timeout=="number"){let s=U(n,{milliseconds:e.timeout});return s.cancel=()=>{r(),s.clear()},s}return n}function M(o,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let r=J(o,t,e),n=r.then(s=>s[0]);return n.cancel=r.cancel,n}function W(o){return o.reason}async function R(o,t,e){if(t==null)return o;let r=e?.translateError??W;if(t.aborted)return o.catch(()=>{}),Promise.reject(r(t));let n;try{return await Promise.race([o,new Promise((s,a)=>{n=()=>{a(r(t))},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var _="/ipfs/ping/1.0.0";var j="1.0.0",k="ping",F="ipfs";var v=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(t,e={}){this.components=t,this.started=!1,this.protocol=`/${e.protocolPrefix??F}/${k}/${j}`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[S]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(t,e){let r=t.log.newScope("ping");r.trace("ping from %p",e.remotePeer);let n=AbortSignal.timeout(this.timeout);n.addEventListener("abort",()=>{t.abort(new w("Ping timed out"))});let s=Date.now();for await(let a of t){if(t.status!=="open"){r("stream status changed to %s",t.status);break}t.send(a)||(r("waiting for stream to drain"),await M(t,"drain",{rejectionEvents:["close"],signal:n}),r("stream drained"))}r("ping from %p complete in %dms",e.remotePeer,Date.now()-s),await t.close({signal:n})}async ping(t,e={}){let r=L(32),n=await this.components.connectionManager.openStream(t,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...e}),s=n.log.newScope("ping");try{let a=Date.now(),u=Promise.withResolvers(),f=new E,m=l=>{if(f.append(l.data),f.byteLength===32){n.removeEventListener("message",m);let i=Date.now()-a;Promise.all([n.closeRead(e)]).then(()=>{if(x(r,f.subarray()))u.resolve(i);else throw new g(`Received wrong ping ack after ${i}ms`)}).catch(h=>{n.abort(h),u.reject(h)})}};return n.addEventListener("message",m),n.send(r),await n.close(e),await R(u.promise,e.signal)}catch(a){throw s.error("error while pinging %o - %e",t,a),n?.abort(a),a}finally{n?.close()}}};function rt(o={}){return t=>new v(t,o)}return z(nt);})();
|
|
2
|
+
"use strict";var Libp2PPing=(()=>{var A=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var X=(o,t)=>{for(var e in t)A(o,e,{get:t[e],enumerable:!0})},q=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $(t))!G.call(o,n)&&n!==e&&A(o,n,{get:()=>t[n],enumerable:!(r=H(t,n))||r.enumerable});return o};var Y=o=>q(A({},"__esModule",{value:!0}),o);var et={};X(et,{PING_PROTOCOL:()=>M,ping:()=>tt});var g=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var w=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}},x=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var P=Symbol.for("@libp2p/service-capabilities"),ot=Symbol.for("@libp2p/service-dependencies");function y(o,t){if(o===t)return!0;if(o.byteLength!==t.byteLength)return!1;for(let e=0;e<o.byteLength;e++)if(o[e]!==t[e])return!1;return!0}function p(o=0){return new Uint8Array(o)}function d(o=0){return new Uint8Array(o)}function T(o,t){t==null&&(t=o.reduce((n,s)=>n+s.length,0));let e=d(t),r=0;for(let n of o)e.set(n,r),r+=n.length;return e}var N=Symbol.for("@achingbrain/uint8arraylist");function S(o,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let r of o){let n=e+r.byteLength;if(t<n)return{buf:r,index:t-e};e=n}throw new RangeError("index is out of bounds")}function E(o){return!!o?.[N]}var L=class o{bufs;length;[N]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else if(E(r))e+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else if(E(r))e+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=S(this.bufs,t);return e.buf[e.index]}set(t,e){let r=S(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else if(E(t))for(let r=0;r<t.length;r++)this.set(e+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:r,length:n}=this._subList(t,e);return T(r,n)}subarray(t,e){let{bufs:r,length:n}=this._subList(t,e);return r.length===1?r[0]:T(r,n)}sublist(t,e){let{bufs:r,length:n}=this._subList(t,e),s=new o;return s.length=n,s.bufs=[...r],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],c=n,u=c+i.byteLength;if(n=u,t>=u)continue;let m=t>=c&&t<u,h=e>c&&e<=u;if(m&&h){if(t===c&&e===u){r.push(i);break}let a=t-c;r.push(i.subarray(a,a+(e-t)));break}if(m){if(t===0){r.push(i);continue}r.push(i.subarray(t-c));continue}if(h){if(e===u){r.push(i);break}r.push(i.subarray(0,e-c));break}r.push(i)}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!E(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let a=0;a<s;a++)i[a]=-1;for(let a=0;a<n;a++)i[r[a]]=a;let c=i,u=this.byteLength-r.byteLength,m=r.byteLength-1,h;for(let a=e;a<=u;a+=h){h=0;for(let l=m;l>=0;l--){let f=this.get(a+l);if(r[l]!==f){h=Math.max(1,l-c[f]);break}}if(h===0)return a}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let r=d(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){let n=p(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let r=d(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){let n=p(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(t==null||!(t instanceof o)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!y(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let r=new o;return r.bufs=t,e==null&&(e=t.reduce((n,s)=>n+s.byteLength,0)),r.length=e,r}};function D(o=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(o))}function v(o){if(isNaN(o)||o<=0)throw new g("random bytes length must be a Number bigger than 0");return D(o)}var O=class o extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,o)}},V=o=>o.reason??new DOMException("This operation was aborted.","AbortError");function U(o,t){let{milliseconds:e,fallback:r,message:n,customTimers:s={setTimeout,clearTimeout},signal:i}=t,c,u,h=new Promise((a,l)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){l(V(i));return}if(i&&(u=()=>{l(V(i))},i.addEventListener("abort",u,{once:!0})),o.then(a,l),e===Number.POSITIVE_INFINITY)return;let f=new O;c=s.setTimeout.call(void 0,()=>{if(r){try{a(r())}catch(b){l(b)}return}typeof o.cancel=="function"&&o.cancel(),n===!1?a():n instanceof Error?l(n):(f.message=n??`Promise timed out after ${e} milliseconds`,l(f))},e)}).finally(()=>{h.clear(),u&&i&&i.removeEventListener("abort",u)});return h.clear=()=>{s.clearTimeout.call(void 0,c),c=void 0},h}var K=o=>{let t=o.addEventListener||o.on||o.addListener,e=o.removeEventListener||o.off||o.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(o),removeListener:e.bind(o)}};function z(o,t,e){let r,n=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let c=[t].flat(),u=[],{addListener:m,removeListener:h}=K(o),a=async(...f)=>{let b=e.multiArgs?f:f[0];if(e.filter)try{if(!await e.filter(b))return}catch(F){r(),i(F);return}u.push(b),e.count===u.length&&(r(),s(u))},l=(...f)=>{r(),i(e.rejectionMultiArgs?f:f[0])};r=()=>{for(let f of c)h(f,a);for(let f of e.rejectionEvents)c.includes(f)||h(f,l)};for(let f of c)m(f,a);for(let f of e.rejectionEvents)c.includes(f)||m(f,l);e.signal&&e.signal.addEventListener("abort",()=>{l(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(u)});if(n.cancel=r,typeof e.timeout=="number"){let s=U(n,{milliseconds:e.timeout});return s.cancel=()=>{r(),s.clear()},s}return n}function C(o,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let r=z(o,t,e),n=r.then(s=>s[0]);return n.cancel=r.cancel,n}function Q(o){return o.reason}async function B(o,t,e){if(t==null)return o;let r=e?.translateError??Q;if(t.aborted)return o.catch(()=>{}),Promise.reject(r(t));let n;try{return await Promise.race([o,new Promise((s,i)=>{n=()=>{i(r(t))},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var M="/ipfs/ping/1.0.0";var R="1.0.0",j="ping",_="ipfs";var I=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(t,e={}){this.components=t,this.started=!1,this.protocol=`/${e.protocolPrefix??_}/${j}/${R}`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[P]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(t,e){let r=t.log.newScope("ping");r.trace("ping from %p",e.remotePeer);let n=AbortSignal.timeout(this.timeout);n.addEventListener("abort",()=>{t.abort(new x("Ping timed out"))});let s=Date.now();for await(let i of t){if(t.status!=="open"){r("stream status changed to %s",t.status);break}t.send(i)||(r("waiting for stream to drain"),await C(t,"drain",{rejectionEvents:["close"],signal:n}),r("stream drained"))}r("ping from %p complete in %dms",e.remotePeer,Date.now()-s),await t.close({signal:n})}async ping(t,e={}){let r=v(32),n=await this.components.connectionManager.openStream(t,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...e}),s=n.log.newScope("ping");try{let i=Date.now(),c=Promise.withResolvers(),u=new L,m=h=>{if(u.append(h.data),u.byteLength===32){n.removeEventListener("message",m);let a=Date.now()-i;Promise.all([n.closeRead(e)]).then(()=>{if(y(r,u.subarray()))c.resolve(a);else throw new w(`Received wrong ping ack after ${a}ms`)}).catch(l=>{n.abort(l),c.reject(l)})}};return n.addEventListener("message",m),n.send(r),await n.close(e),await B(c.promise,e.signal)}catch(i){throw s.error("error while pinging %o - %e",t,i),n?.abort(i),i}finally{n?.close()}}};function tt(o={}){return t=>new I(t,o)}return Y(et);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/utils.js:
|
package/dist/index.min.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../../interface/src/errors.ts", "../../interface/src/index.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/@noble/hashes/src/utils.ts", "../../crypto/src/random-bytes.ts", "../../../node_modules/p-timeout/index.js", "../../../node_modules/p-event/index.js", "../../../node_modules/race-signal/src/index.ts", "../src/constants.ts", "../src/ping.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\n\nimport { Ping as PingClass } from './ping.js'\nimport type { AbortOptions, PeerId } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface Ping {\n ping(peer: PeerId | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<number>\n}\n\nexport interface PingInit {\n protocolPrefix?: string\n maxInboundStreams?: number\n maxOutboundStreams?: number\n runOnLimitedConnection?: boolean\n\n /**\n * How long we should wait for a ping response\n */\n timeout?: number\n}\n\nexport interface PingComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport function ping (init: PingInit = {}): (components: PingComponents) => Ping {\n return (components) => new PingClass(components, init)\n}\n\nexport { PING_PROTOCOL } from './constants.js'\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\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", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/** Merges default options and passed options. */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash<T> {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash constructor */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: HashInfo = {}\n): CHash<T, Opts> {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required<HashInfo> => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils.js'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\n}\n", "export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "export const PING_PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\nexport const PROTOCOL_PREFIX = 'ipfs'\nexport const TIMEOUT = 10000\n\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2\nexport const MAX_OUTBOUND_STREAMS = 1\n", "import { randomBytes } from '@libp2p/crypto'\nimport { ProtocolError, serviceCapabilities, setMaxListeners, TimeoutError } from '@libp2p/interface'\nimport { pEvent } from 'p-event'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js'\nimport type { PingComponents, PingInit, Ping as PingInterface } from './index.js'\nimport type { AbortOptions, Stream, PeerId, Startable, Connection, StreamMessageEvent } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport class Ping implements Startable, PingInterface {\n public readonly protocol: string\n private readonly components: PingComponents\n private started: boolean\n private readonly timeout: number\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n private readonly runOnLimitedConnection: boolean\n\n constructor (components: PingComponents, init: PingInit = {}) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.timeout = init.timeout ?? TIMEOUT\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS\n this.runOnLimitedConnection = init.runOnLimitedConnection ?? true\n\n this.handlePing = this.handlePing.bind(this)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/ping'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/ping'\n ]\n\n async start (): Promise<void> {\n await this.components.registrar.handle(this.protocol, this.handlePing, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnLimitedConnection: this.runOnLimitedConnection\n })\n this.started = true\n }\n\n async stop (): Promise<void> {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n async handlePing (stream: Stream, connection: Connection): Promise<void> {\n const log = stream.log.newScope('ping')\n log.trace('ping from %p', connection.remotePeer)\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n signal.addEventListener('abort', () => {\n stream.abort(new TimeoutError('Ping timed out'))\n })\n const start = Date.now()\n\n for await (const buf of stream) {\n if (stream.status !== 'open') {\n log('stream status changed to %s', stream.status)\n break\n }\n\n if (!stream.send(buf)) {\n log('waiting for stream to drain')\n await pEvent(stream, 'drain', {\n rejectionEvents: [\n 'close'\n ],\n signal\n })\n log('stream drained')\n }\n }\n\n log('ping from %p complete in %dms', connection.remotePeer, Date.now() - start)\n\n await stream.close({\n signal\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise<number> {\n const data = randomBytes(PING_LENGTH)\n const stream = await this.components.connectionManager.openStream(peer, this.protocol, {\n runOnLimitedConnection: this.runOnLimitedConnection,\n ...options\n })\n const log = stream.log.newScope('ping')\n\n try {\n const start = Date.now()\n const finished = Promise.withResolvers<number>()\n const received = new Uint8ArrayList()\n\n const onPong = (evt: StreamMessageEvent): void => {\n received.append(evt.data)\n\n if (received.byteLength === PING_LENGTH) {\n stream.removeEventListener('message', onPong)\n\n const rtt = Date.now() - start\n\n Promise.all([\n stream.closeRead(options)\n ])\n .then(() => {\n if (!uint8ArrayEquals(data, received.subarray())) {\n throw new ProtocolError(`Received wrong ping ack after ${rtt}ms`)\n } else {\n finished.resolve(rtt)\n }\n })\n .catch(err => {\n stream.abort(err)\n finished.reject(err)\n })\n }\n }\n\n stream.addEventListener('message', onPong)\n stream.send(data)\n await stream.close(options)\n\n return await raceSignal(finished.promise, options.signal)\n } catch (err: any) {\n log.error('error while pinging %o - %e', peer, err)\n\n stream?.abort(err)\n\n throw err\n } finally {\n stream?.close()\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";8bAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,mBAAAE,EAAA,SAAAC,KCyCM,IAAOC,EAAP,cAAsC,KAAK,CAC/C,OAAO,KAAO,yBAEd,YAAaC,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,wBACd,GA+NI,IAAOC,EAAP,cAA6B,KAAK,CACtC,OAAO,KAAO,gBAEd,YAAaC,EAAU,iBAAgB,CACrC,MAAMA,CAAO,EACb,KAAK,KAAO,eACd,GAMWC,EAAP,cAA4B,KAAK,CACrC,OAAO,KAAO,eAEd,YAAaD,EAAU,YAAW,CAChC,MAAMA,CAAO,EACb,KAAK,KAAO,cACd,GCmoBK,IAAME,EAAsB,OAAO,IAAI,8BAA8B,EAS/DC,GAAsB,OAAO,IAAI,8BAA8B,ECz6BtE,SAAUC,EAAQC,EAAeC,EAAa,CAClD,GAAID,IAAMC,EACR,MAAO,GAGT,GAAID,EAAE,aAAeC,EAAE,WACrB,MAAO,GAGT,QAASC,EAAI,EAAGA,EAAIF,EAAE,WAAYE,IAChC,GAAIF,EAAEE,CAAC,IAAMD,EAAEC,CAAC,EACd,MAAO,GAIX,MAAO,EACT,CCfM,SAAUC,EAAOC,EAAe,EAAC,CACrC,OAAO,IAAI,WAAWA,CAAI,CAC5B,CAOM,SAAUC,EAAaD,EAAe,EAAC,CAC3C,OAAO,IAAI,WAAWA,CAAI,CAC5B,CCTM,SAAUE,EAAQC,EAAsBC,EAAe,CACvDA,GAAU,OACZA,EAASD,EAAO,OAAO,CAACE,EAAKC,IAASD,EAAMC,EAAK,OAAQ,CAAC,GAG5D,IAAMC,EAASC,EAAYJ,CAAM,EAC7BK,EAAS,EAEb,QAAWC,KAAOP,EAChBI,EAAO,IAAIG,EAAKD,CAAM,EACtBA,GAAUC,EAAI,OAGhB,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", "InvalidParametersError", "message", "ProtocolError", "message", "TimeoutError", "serviceCapabilities", "serviceDependencies", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "randomBytes", "bytesLength", "cr", "randomBytes", "length", "InvalidParametersError", "TimeoutError", "
|
|
4
|
+
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\n\nimport { Ping as PingClass } from './ping.js'\nimport type { AbortOptions, PeerId } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface Ping {\n ping(peer: PeerId | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<number>\n}\n\nexport interface PingInit {\n protocolPrefix?: string\n maxInboundStreams?: number\n maxOutboundStreams?: number\n runOnLimitedConnection?: boolean\n\n /**\n * How long we should wait for a ping response\n */\n timeout?: number\n}\n\nexport interface PingComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport function ping (init: PingInit = {}): (components: PingComponents) => Ping {\n return (components) => new PingClass(components, init)\n}\n\nexport { PING_PROTOCOL } from './constants.js'\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\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", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/** Merges default options and passed options. */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash<T> {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash constructor */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: HashInfo = {}\n): CHash<T, Opts> {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required<HashInfo> => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils.js'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\n}\n", "export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t\tsignal,\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "export const PING_PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\nexport const PROTOCOL_PREFIX = 'ipfs'\nexport const TIMEOUT = 10000\n\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2\nexport const MAX_OUTBOUND_STREAMS = 1\n", "import { randomBytes } from '@libp2p/crypto'\nimport { ProtocolError, serviceCapabilities, setMaxListeners, TimeoutError } from '@libp2p/interface'\nimport { pEvent } from 'p-event'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js'\nimport type { PingComponents, PingInit, Ping as PingInterface } from './index.js'\nimport type { AbortOptions, Stream, PeerId, Startable, Connection, StreamMessageEvent } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport class Ping implements Startable, PingInterface {\n public readonly protocol: string\n private readonly components: PingComponents\n private started: boolean\n private readonly timeout: number\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n private readonly runOnLimitedConnection: boolean\n\n constructor (components: PingComponents, init: PingInit = {}) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.timeout = init.timeout ?? TIMEOUT\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS\n this.runOnLimitedConnection = init.runOnLimitedConnection ?? true\n\n this.handlePing = this.handlePing.bind(this)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/ping'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/ping'\n ]\n\n async start (): Promise<void> {\n await this.components.registrar.handle(this.protocol, this.handlePing, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnLimitedConnection: this.runOnLimitedConnection\n })\n this.started = true\n }\n\n async stop (): Promise<void> {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n async handlePing (stream: Stream, connection: Connection): Promise<void> {\n const log = stream.log.newScope('ping')\n log.trace('ping from %p', connection.remotePeer)\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n signal.addEventListener('abort', () => {\n stream.abort(new TimeoutError('Ping timed out'))\n })\n const start = Date.now()\n\n for await (const buf of stream) {\n if (stream.status !== 'open') {\n log('stream status changed to %s', stream.status)\n break\n }\n\n if (!stream.send(buf)) {\n log('waiting for stream to drain')\n await pEvent(stream, 'drain', {\n rejectionEvents: [\n 'close'\n ],\n signal\n })\n log('stream drained')\n }\n }\n\n log('ping from %p complete in %dms', connection.remotePeer, Date.now() - start)\n\n await stream.close({\n signal\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise<number> {\n const data = randomBytes(PING_LENGTH)\n const stream = await this.components.connectionManager.openStream(peer, this.protocol, {\n runOnLimitedConnection: this.runOnLimitedConnection,\n ...options\n })\n const log = stream.log.newScope('ping')\n\n try {\n const start = Date.now()\n const finished = Promise.withResolvers<number>()\n const received = new Uint8ArrayList()\n\n const onPong = (evt: StreamMessageEvent): void => {\n received.append(evt.data)\n\n if (received.byteLength === PING_LENGTH) {\n stream.removeEventListener('message', onPong)\n\n const rtt = Date.now() - start\n\n Promise.all([\n stream.closeRead(options)\n ])\n .then(() => {\n if (!uint8ArrayEquals(data, received.subarray())) {\n throw new ProtocolError(`Received wrong ping ack after ${rtt}ms`)\n } else {\n finished.resolve(rtt)\n }\n })\n .catch(err => {\n stream.abort(err)\n finished.reject(err)\n })\n }\n }\n\n stream.addEventListener('message', onPong)\n stream.send(data)\n await stream.close(options)\n\n return await raceSignal(finished.promise, options.signal)\n } catch (err: any) {\n log.error('error while pinging %o - %e', peer, err)\n\n stream?.abort(err)\n\n throw err\n } finally {\n stream?.close()\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";8bAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,mBAAAE,EAAA,SAAAC,KCyCM,IAAOC,EAAP,cAAsC,K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AAiBR,EAAMG,EAAS,SAAQ,CAAE,EAG7CD,EAAS,QAAQK,CAAG,MAFpB,OAAM,IAAIE,EAAc,iCAAiCF,CAAG,IAAI,CAIpE,CAAC,EACA,MAAMG,GAAM,CACXpB,EAAO,MAAMoB,CAAG,EAChBR,EAAS,OAAOQ,CAAG,CACrB,CAAC,CACL,CACF,EAEA,OAAApB,EAAO,iBAAiB,UAAWe,CAAM,EACzCf,EAAO,KAAKU,CAAI,EAChB,MAAMV,EAAO,MAAMS,CAAO,EAEnB,MAAMY,EAAWT,EAAS,QAASH,EAAQ,MAAM,CAC1D,OAASW,EAAU,CACjB,MAAAlB,EAAI,MAAM,8BAA+BM,EAAMY,CAAG,EAElDpB,GAAQ,MAAMoB,CAAG,EAEXA,CACR,SACEpB,GAAQ,MAAK,CACf,CACF,GbnGI,SAAUsB,GAAMC,EAAiB,CAAA,EAAE,CACvC,OAAQC,GAAe,IAAIC,EAAUD,EAAYD,CAAI,CACvD",
|
|
6
|
+
"names": ["index_exports", "__export", "PING_PROTOCOL", "ping", "InvalidParametersError", "message", "ProtocolError", "message", "TimeoutError", "serviceCapabilities", "serviceDependencies", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "randomBytes", "bytesLength", "cr", "randomBytes", "length", "InvalidParametersError", "TimeoutError", "_TimeoutError", "message", "options", "getAbortedReason", "signal", "pTimeout", "promise", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "error", "rejectHandler", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "PING_PROTOCOL", "PROTOCOL_VERSION", "PROTOCOL_NAME", "PROTOCOL_PREFIX", "Ping", "components", "init", "PROTOCOL_PREFIX", "PROTOCOL_NAME", "PROTOCOL_VERSION", "serviceCapabilities", "stream", "connection", "log", "signal", "TimeoutError", "start", "buf", "pEvent", "peer", "options", "data", "randomBytes", "finished", "received", "Uint8ArrayList", "onPong", "evt", "rtt", "equals", "ProtocolError", "err", "raceSignal", "ping", "init", "components", "Ping"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@libp2p/ping",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.11-19796b103",
|
|
4
4
|
"description": "Implementation of Ping Protocol",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/protocol-ping#readme",
|
|
@@ -43,9 +43,9 @@
|
|
|
43
43
|
"doc-check": "aegir doc-check"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@libp2p/crypto": "
|
|
47
|
-
"@libp2p/interface": "
|
|
48
|
-
"@libp2p/interface-internal": "
|
|
46
|
+
"@libp2p/crypto": "5.1.13-19796b103",
|
|
47
|
+
"@libp2p/interface": "3.1.0-19796b103",
|
|
48
|
+
"@libp2p/interface-internal": "3.0.11-19796b103",
|
|
49
49
|
"@multiformats/multiaddr": "^13.0.1",
|
|
50
50
|
"p-event": "^7.0.0",
|
|
51
51
|
"race-signal": "^2.0.0",
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"uint8arrays": "^5.1.0"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
|
-
"@libp2p/peer-id": "
|
|
57
|
-
"@libp2p/utils": "
|
|
56
|
+
"@libp2p/peer-id": "6.0.4-19796b103",
|
|
57
|
+
"@libp2p/utils": "7.0.11-19796b103",
|
|
58
58
|
"aegir": "^47.0.22",
|
|
59
59
|
"delay": "^7.0.0",
|
|
60
60
|
"sinon": "^21.0.0",
|
package/dist/typedoc-urls.json
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"Ping": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_ping.Ping.html",
|
|
3
|
-
".:Ping": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_ping.Ping.html",
|
|
4
|
-
"PingComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_ping.PingComponents.html",
|
|
5
|
-
".:PingComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_ping.PingComponents.html",
|
|
6
|
-
"PingInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_ping.PingInit.html",
|
|
7
|
-
".:PingInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_ping.PingInit.html",
|
|
8
|
-
"PING_PROTOCOL": "https://libp2p.github.io/js-libp2p/variables/_libp2p_ping.PING_PROTOCOL.html",
|
|
9
|
-
"ping": "https://libp2p.github.io/js-libp2p/functions/_libp2p_ping.ping.html",
|
|
10
|
-
".:ping": "https://libp2p.github.io/js-libp2p/functions/_libp2p_ping.ping.html"
|
|
11
|
-
}
|